在阅读相关问题#1,#2后, 我仍然没有找到以下问题的答案:
Javascript可以this使用:bind,call和设置上下文(即设置) apply.
但是当我写一个事件处理程序时:
document.getElementById('myInput').onclick = function ()
{
alert(this.value)
}
Run Code Online (Sandbox Code Playgroud)
谁/什么实际上附着 this在object自己身上?
PS使用jQuery时:
$("#myInput").bind(function (){...})
Run Code Online (Sandbox Code Playgroud)
有是内部实现的(bind,call或apply)
所以,当我不使用jQuery时,谁在做呢?
在jquery中,事件hadler的绑定是生成DOM元素的事件(这指向dom元素).在原型中更改事件处理程序的绑定,可以使用bindAsEventListener函数; 如何从事件处理程序访问实例和DOM元素?
类似于如何将事件处理程序绑定到JQuery中的实例?
function Car(){
this.km = 0;
$("#sprint").click(this.drive); //setup event handler
}
// event handler
// in it I need to access both the clicked element
// and the binding object (instance of car)
Car.prototype.drive = function(){
this.km += 10; // i'd like to access the binding (but jq changes it)
this.css({ // also the element
left: this.km
});
// NOTE that is inside this function I want to access them not elsewhere
}
var car …Run Code Online (Sandbox Code Playgroud)