0

您好,我在以下代码段中收到错误 this._radioButtons 未定义(** 之间的代码)。我在这里缺少关于关闭的东西吗?

_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作为第三个参数以强制上下文:

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-pointer 甚至将其命名为this_adustChoices...

于 2013-02-06T13:17:25.890 回答