0

こんにちは、次のスニペットで this._radioButtons is undefined (the code between **) というエラーが表示されます。ここで見逃している閉鎖について何かありますか?

_adjustChoices: function(choices) {
            // TODO Tear down all the old radion buttons and their change handlers.
            debugger;
            this._radioButtons = [];
            this._changeHandlers = [];
            array.forEach(choices, function(choice) {
                var radioButton = new RadioButton(lang.mixin({
                    name: this._clusterName
                }, choice));
                **this._radioButtons.push(radioButton);**
                this._changeHandlers.push(connect.connect, radioButton, "onChange", lang.hitch(this, function(value) {
                    // TODO Figure out which radio button is selected and get its value.
                    //var radioButton = ????;
                    this.set("value", radioButton.get("checked"));
                }));
            });
        },
4

2 に答える 2

2

array.forEach(choices, function(choice) { /* your code here*/ })コールバック関数内にいるためthis、関数を参照しています。thisコンテキストを強制する 3 番目の引数として追加します。

array.forEach(choices, function(choice) { 

    // YOUR CODE HERE

}, this);  // => here
于 2013-02-06T07:09:37.290 に答える
0

私の個人的な意見では、バグのある関数スコープの外側にある種のポインタを宣言することで、読みやすさを向上させることができます。

// code code code
_adjustChoices: function(choices) {
    var _this = this;
    // rest of your code...

    array.forEach(choices, function(choice) {
        //stuff you do
        var radioButton = new RadioButton(lang.mixin({
                name: _this._clusterName                //access it this way
            }, choice));
    }
}

そうすれば、各thisポインタにアクセスしthis_adustChoicesたり、好きな名前を付けたりすることもできます...

于 2013-02-06T13:17:25.890 に答える