修改函数以从类外部访问私有变量

modify function to access private variable from outside a class

本文关键字:访问 变量 外部 函数 修改      更新时间:2023-12-15

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

您忘记将new关键字与bestfriends一起使用。

应该像timon_pubmaa.getSecret()一样在实例上调用getSecret

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

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!