1

标题有点模棱两可,但代码非常清楚地解释了这个问题:

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 。

4

3 回答 3

2

您必须thisGame函数中创建一个副本。规范的做法是创建一个名为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 上看到这一点

于 2013-02-28T02:02:49.363 回答
2

在您的代码中,您需要对访问变量的方式进行一些更改secret-您可以通过将this关键字复制到that像彼得的答案这样的变量中来做到这一点。

另一种方式可能是这样的:

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

Because of the Game function enclosure the secret variable is private to that scope. And as long as you define your functions within that enclosure, those functions will have access to the secret "private" variable.

于 2013-02-28T02:08:51.593 回答
0

(我在 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);
        }
    };
}
于 2013-02-28T02:07:03.457 回答