对于以下示例,我有两个问题:
function doIt(){
this.attribute = someValue; // Works as expected
alert(event.which); // Doesn't work
}
element.addEventListener("click",doIt,false);
问题1:为什么this
被绑定到函数而event
没有被绑定?
问题2:应该如何正确处理这个问题?
对于以下示例,我有两个问题:
function doIt(){
this.attribute = someValue; // Works as expected
alert(event.which); // Doesn't work
}
element.addEventListener("click",doIt,false);
问题1:为什么this
被绑定到函数而event
没有被绑定?
问题2:应该如何正确处理这个问题?
this
是JavaScript的内置对象,始终可访问。而event
不是,它仅在当前方法支持时才可用。
您需要像下面这样:
function doIt(event)
什么是 this
?- http://howtonode.org/what-is-this
this
是内置的,但我不理解this
如何引用回元素,我认为它应该引用函数本身。我尝试使用addEventListener("click",function(){doit(event);}来修复event
,但这会破坏this
。似乎有比传递两者更好的方法。抱歉,绑定是我难以掌握的东西... - Garythis
指当前对象,您的方法不是一个对象,而是一个方法
。因此,唯一可用的对象
是所选元素。 - Korvin Szantothis
是从调用者传递给函数的。下面有原型,所以您可以看到代码如何工作-https://developer.mozilla.org/en/DOM/element.addEventListener#section_8 - mrtshermandoIt():doIt(event):doIt(event, b, c, d)
都是有效的。 - mrtsherman