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

this関数内で のコピーを作成する必要がありGameます。標準的なことは、 という変数を作成することです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コピーすることでそれを行うことができます.thisthat

別の方法は次のようになります。

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

関数の囲い込みのためGame、シークレット変数はそのスコープに対してプライベートです。そして、そのエンクロージャー内で関数を定義している限り、それらの関数は秘密の「プライベート」変数にアクセスできます。

于 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 に答える