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; }
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?
(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.)
The following ought to do it:
The
call()function attached toFunctionobjects 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.