我想修改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