我有一个带有原型(prototype)方法的 Javascript 类,该方法使用 for 循环将事件监听器添加到一组对象并调用类中的另一个方法。
为了能够访问类中的其他方法,我必须在事件监听器中绑定(bind)函数,使我能够访问其他类方法。然而,我总是在 for 循环中获得最高值,所以我在匿名函数中返回一个函数,但现在我无法让绑定(bind)函数工作并找到其他类方法。
ToDoList.prototype = {
addListener : function(){
//inside for loop
for(var i = 0; i < ToDoList.counter; i++){
el.addEventListener("click", ((function(value){
return function(){
this.remove(value); //trying to call this method
};
})(i)).bind(this)
);
}
}
remove : function(index){
//do some stuff if you can get to me
}
}
上面的代码只适用于 for 循环的最后一个值。有什么方法可以让代码处理 for 循环中的所有值。
最佳答案
bind
函数返回一个新函数,其中 this
设置为 bind
的第一个参数,所有后续参数都作为参数传递。
如果使用 bind
,则不需要闭包:
ToDoList.prototype = {
addListener: function() {
for (var i = 0; i < ToDoList.counter; i++) {
el.addEventListener("click", function(value) {
// `this` is the same as outer `this`
// `value` is `i`
this.remove(value);
}.bind(this, i));
}
},
remove: function(index) {
}
}
关于javascript - 在 for 循环中将 Bind 添加到 vanilla Javascript 中的原型(prototype)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40204224/