2015-02-17 133 views
-1

我想修改getSecret函数以使私有变量'secret'可以从'bestfriends'类之外访问。修改函数以访问类之外的私有变量

任何想法?

function bestfriends(name1, name2) { 
this.friend1 = name1; 
this.friend2 = name2; 
var secret = "Hakuna Matata!"; 
console.log (this.friend1 + ' and ' + this.friend2 + ' are the best of friends! '); 
} 

bestfriends.prototype.getSecret = function() { 
    return secret 
} 

var timon_pubmaa = bestfriends('timon', 'pumbaa'); 

var timon_pumbaa_secret = getSecret(); 

console.log(timon_pumbaa_secret); 
+1

1.'变种timon_pubmaa =新bestfriends( '蒂莫', '彭彭');''2.变种timon_pumbaa_secret = timon_pubmaa.getSecret();''3.返回this.secret' 4.'此.secret = ...'或者在构造函数中移动getSecret'实现并使用闭包。 – zerkms 2015-02-17 20:27:20

+0

你不能。您可以将该属性设为公共或公开属性,也可以从相同范围公开该属性,但不能修改对私有属性范围的访问权限。 – Mathletics 2015-02-17 23:44:44

回答

0

您忘记使用new关键字bestfriends

getSecret应该在​​这样的实例上调用。

您的secret变量是构造函数的本地变量,它不能从该方法访问。为了达到这个目的,你可以创建一个闭包并返回你的构造函数,并且在闭包中你可以创建一些私有的变量。

var bestfriends = (function() { 

    var secret; // private variable 

    function bestfriends(name1, name2) { 
     this.friend1 = name1; 
     this.friend2 = name2; 
     secret = "Hakuna Matata!"; 
     console.log(this.friend1 + ' and ' + this.friend2 + ' are the best of friends! '); 
    } 

    bestfriends.prototype.getSecret = function() { 
     return secret 
    } 

    return bestfriends; 

})(); 

var timon_pubmaa = new bestfriends('timon', 'pumbaa'); 
var timon_pumbaa_secret = timon_pubmaa.getSecret(); 
console.log(timon_pumbaa_secret); // Hakuna Matata! 
+0

当我输入上面的代码时,我得到“ReferenceError:getSecret没有定义” – mdarmanin 2015-02-17 20:39:15

+0

如果'secret'变量是静态的(可以被整个类访问),你不应该从构造函数初始化它。 – Bergi 2015-02-17 21:04:25

+0

我已经走了并在代码顶部添加了秘密变量,但我仍然得到相同的结果:“ReferenceError:getSecret未定义” – mdarmanin 2015-02-17 21:20:39