JavaScript:将对象的方法绑定到事件处理程序 [英] JavaScript: bind an object's method to event handler
问题描述
根据John Resig的学习高级JavaScript( http://ejohn.org/apps/learn /#83 )将对象的方法绑定到事件处理程序而不将原始对象作为上下文传递是不正确的,但我发现该示例存在缺陷。它声称被点击的属性被意外设置。这是一个反例。
According to John Resig's 'Learning Advanced JavaScript' (http://ejohn.org/apps/learn/#83) it's incorrect to bind an object's method to event handler without passing the original object as context, however I find the example flawed. It claims the clicked property gets set accidentally. Here's a counter-example.
var Button = {
click: function(){
this.clicked = true;
console.log( elem.clicked );
}
};
var elem = document.createElement("li");
elem.innerHTML = "Click me!";
elem.onclick = Button.click;
document.children[0].appendChild(elem);
console.log( !elem.clicked );
必须有其他理由不这样做。它是什么?
There must be another reason not to do this. What is it?
推荐答案
在任何对象方法中,此
始终引用在上调用方法的对象。所有JavaScript都适用此
提供调用上下文,而不是方法所有者 (*)。
In any object method, this
always refers to the object the method has been called on. It's true for all JavaScript that this
provides the calling context, not the method owner (*).
var sample = {
foo: function () {
this.clicked = true;
}
}
sample.foo(); // 'this' refers to 'sample'
alert(sample.clicked) // true
在事件处理程序中,此
指的是触发事件的元素。这意味着当您将对象方法传递给单击
事件...
In an event handler this
refers to the element that triggered the event. This means when you pass an object method to the click
event...
var div = document.getElementById("test");
div.onclick = sample.foo;
然后 foo()
将是调用 DOM元素,即使它已在别处定义。
then foo()
will be called on the DOM element, even though it has been defined elsewhere.
/* ... click the div ... */
alert(sample.clicked); // false
alert(div.clicked); // true
会导致意外结果。
(*)这是因为从技术上讲,JavaScript中没有方法所有者。方法是恰好由对象属性引用的独立函数。可以很容易地在不同的对象中存储对同一函数的引用( div.onclick = sample.foo
)。
(*) That's because technically there is no method owner in JavaScript. Methods are standalone functions that happen to be referenced by object properties. Storing a reference to the same function in a different object (div.onclick = sample.foo
does just that) is easily possible.
因此, obj.method()
是语法糖。
function func() { /* ... */ }
var obj = {
method: func
};
obj.method();
func.call(obj); // same thing
这篇关于JavaScript:将对象的方法绑定到事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!