当 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 是如何做到这一点的?我想为我自己的自定义框架复制此行为。
最佳答案
函数
有两种可以使用的方法:call和 apply 。对于这两者,将要用于 this
的对象作为第一个参数传递。使用call
,附加参数被一一传递:
functionName.call(this, arg1, arg2);
使用apply
,传入参数数组:
functionName.apply(this, [arg1, arg1]);
或者,您可以传递实际参数对象:
function someFunction ()
{
functionName.apply(this, this.arguments);
}
关于javascript:在函数上下文中定义 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707489/