当jQuery调用一个函数作为引发事件的事件处理程序时,jQuery能够以某种方式在它所调用的函数的上下文中定义"this“。在下面的示例中,jQuery将其定义为被单击的dom元素。
<input id="someButton" type="button" value="click me!"/>
<script type="text/javascript">
$("#someButton").click(EventHandler);
function EventHandler()
{
alert($(this).attr("id")); //This raises an alert message "someButton"
}
</script>jQuery是如何做到这一点的?我想将这种行为复制到我自己的自定义框架中。
发布于 2011-04-19 02:57:02
Function有两种方法可供使用:call和apply。使用这两个参数,传递要用于this的对象作为第一个参数。使用call,额外的参数一个接一个地传递:
functionName.call(this, arg1, arg2);使用apply传入一个参数数组:
functionName.apply(this, [arg1, arg1]);或者,您可以传递一个实际的参数对象:
function someFunction ()
{
functionName.apply(this, this.arguments);
}发布于 2011-04-19 02:57:37
您可以使用call或apply JavaScript方法:
function myFunction() {
// you want "this" to be your element
}
var element = SOMEDOMELEMENT;
myFunction.call(element, /* add other comma-separated arguments here, if any */);
myFunction.apply(element, /* add an array of arguments here, if any */);当使用call和apply时,它会将函数中的上下文(this)更改为您想要的任何元素。
发布于 2011-04-19 02:56:40
不确定jQuery使用的是什么,但有一个bind函数:
var regularFunc = function() {
console.log(this);
};
var boundFunc = regularFunc.bind(123);
regularFunc(); // logs whatever 'this' is at time it is called (e.g. 'window')
boundFunc(); // logs 123 at all times since that is specified to be 'this'https://stackoverflow.com/questions/5707489
复制相似问题