Simple javascript to mimic jQuery behaviour of using this in events handlers

一曲冷凌霜 提交于 2019-12-01 17:59:20

In Javascript, you can call a function programmatically and tell it what this should refer to, and pass it some arguments using either the call or apply method in Function. Function is an object too in Javascript.

jQuery iterates through every matching element in its results, and calls the click function on that object (in your example) passing the element itself as the context or what this refers to inside that function.

For example:

function alertElementText() {
    alert(this.text());
}

This will call the text function on the context (this) object, and alert it's value. Now we can call the function and make the context (this) to be the jQuery wrapped element (so we can call this directly without using $(this).

<a id="someA">some text</a>
alertElementText.call($("#someA")); // should alert "some text"

The distinction between using call or apply to call the function is subtle. With call the arguments will be passed as they are, and with apply they will be passed as an array. Read up more about apply and call on MDC.

Likewise when a DOM event handler is called, this already points to the element that triggered the event. jQuery just calls your callback and sets the context to the element.

document.getElementById("someId").onclick = function() {
    // this refers to #someId here
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!