2013-02-06 54 views
0

嗨,我收到了錯誤this._radioButtons未定義(**之間的代碼)在下面的代碼片段。有什麼關於我在這裏失蹤的關閉?this.variable is undefined

_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")); 
       })); 
      }); 
     }, 

回答

2

你在裏面array.forEach(choices, function(choice) { /* your code here*/ })回調函數,因此this指功能。添加this作爲第三個參數來強制上下文:

array.forEach(choices, function(choice) { 

    // YOUR CODE HERE 

}, this); // => here 
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或什麼...