我想修改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.'变种timon_pubmaa =新bestfriends( '蒂莫', '彭彭');''2.变种timon_pumbaa_secret = timon_pubmaa.getSecret();''3.返回this.secret' 4.'此.secret = ...'或者在构造函数中移动getSecret'实现并使用闭包。 – zerkms 2015-02-17 20:27:20
你不能。您可以将该属性设为公共或公开属性,也可以从相同范围公开该属性,但不能修改对私有属性范围的访问权限。 – Mathletics 2015-02-17 23:44:44