2013-02-06 93 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或什么...