使用“this”调用函数。 [英] Call function with "this"
问题描述
我有一个< a>的onclick处理程序element(实际上,它是一个jQuery创建的处理程序,但这并不重要)。它看起来像这样:
I have an onclick handler for an <a> element (actually, it's a jQuery-created handler, but that's not important). It looks like this:
function handleOnClick() {
if(confirm("Are you sure?")) {
return handleOnClickConfirmed();
}
return false;
}
从此功能可以访问此对象作为< a>元素点击。但是,handleOnClickConfirmed的 this 是一个Window元素!我希望handleOnClickConfirmed与handleOnClick具有相同的 this 。我该怎么做?
From this function, the this object is accessable as the <a> element clicked. However, handleOnClickConfirmed's this is a Window element! I want handleOnClickConfirmed to have the same this as handleOnClick does. How would I do this?
(我知道我可以将 this 作为handleOnClickConfirmed的参数传递,但我的一些代码已经使用了handleOnClickConfirmed和我不想重写那些电话。此外,我认为使用这个看起来更干净。)
(I know I can pass this as an argument to handleOnClickConfirmed, but some of my code already uses handleOnClickConfirmed and I don't want to have to rewrite those calls. Besides, I think using this looks cleaner.)
推荐答案
以下应该这样做:
function handleOnClick() {
if( confirm( "Sure?" ) ) {
return handleOnClickConfirmed.call( this );
}
return false;
}
call()
附加到函数的函数
对象旨在允许这个;调用具有所需上下文的函数。在设置调用其他对象中的函数的事件处理程序时,这是一个非常有用的技巧。
The call()
function attached to Function
objects is designed to allow this; calling a function with a desired context. It's an extremely useful trick when setting up event handlers that call back into functions within other objects.
这篇关于使用“this”调用函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!