将 init 函数的 this
参数传递给更改事件处理程序的最佳方法是什么?为什么?
选项 1(使用 that = this)。
SomeObject.prototype.init = function () {
var that = this;
this.$element.change(function () {
//do some some things with that.
that.
});
};
选项 2(使用 event.data )。
SomeObject.prototype.init = function () {
this.$element.change({object:this }, function (e) {
//do some some things with the event data.
e.data.object.
});
};
或者另一个(更好的)?
最佳答案
恕我直言,第一个更好一点。第三种方法(如果你可以使用 ECMA5)是
SomeObject.prototype.init = function () {
this.$element.change(function () {
//do some some things with this.
this.
}.bind(this));
};
关于javascript - 哪种解决方案更适合将 "this"参数传递给 javascript 事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8779749/