从封装对象访问对象中的变量

Access a variable in an object from an encapsulate one

本文关键字:对象 变量 访问 封装      更新时间:2023-09-26

标题有点模棱两可,但代码解释得很清楚:

function Game() {
    this.secret = '';
    this.Playground = {
        this.someTreat: function() {
            console.log('how to access secret from here ?');
        }
    };
}
var Test = new Game();
Test.Playground.someTreat();

我提供了一个具有相同代码的JSFiddle

在您的代码中,您需要对如何访问变量secret进行一些更改-您可以将this关键字复制到that变量中,如Peter的答案。

另一种方式是:

function Game() {
  var secret = 'secret information';
  this.Playground = {
    this.someTreat = function() {
        console.log(secret);
    };
  };
}

由于Game函数外壳,秘密变量对该作用域是私有的。只要你在这个框内定义你的函数,这些函数就可以访问秘密的"private"变量。

您必须在Game函数中创建this的副本。规范的做法是创建一个名为that的变量。

function Game() {
    this.secret = 'secret information';
    var that = this;
    this.Playground = {
        someTreat: function() {
            console.log(that.secret);
        }
    };
}
var test = new Game();
test.Playground.someTreat();

您可以在jsFiddle上看到这个操作

(我修复了您在Playground和someTreat定义中的错误)

在'this'上使用闭包:

function Game() {
    var self = this;
    this.secret = 'xyz';
    this.Playground = {
        someTreat: function() {
            console.log('how to access secret from here ?');
            console.log('response: use self');
            console.log('self.secret: ' + self.secret);
        }
    };
}