关于(绑定)`this`的属性是未定义的 - 上下文问题?

时间:2014-08-11 13:14:41

标签: javascript javascript-events this

我在此currentRowIndex函数中遇到变量init的范围问题。在onclickevent函数中,this.currentRowIndex未定义。任何人都可以看到我所做的事情的问题是什么,因为我在事件处理程序上使用了.bind(),我希望它能够正常工作。

 init: function() {

        this.getTable().addEventHandler("rowclick", function(row, model) {
                    this.currentRowIndex = row.element.element.rowIndex-1;
        }.bind(this));

        this.removeIcon = new Icon({
            onclickevent: function() {

          //this.currentRowIndex is undefined here(don't know why)
                this.getEventBus().publish("cell-link-clicked", this.currentRowIndex);
            }.bind(this)
        });
    },

1 个答案:

答案 0 :(得分:-2)

init: function() {
    var that = this;
        this.getTable().addEventHandler("rowclick", function(row, model) {
                    that.currentRowIndex = row.element.element.rowIndex-1;
        });

        this.removeIcon = new Icon({
            onclickevent: function() {

          //this.currentRowIndex is undefined here(don't know why)
                that.getEventBus().publish("cell-link-clicked", this.currentRowIndex);
            }
        });
    },