Can someone explain to me the importance of using function wrappers (ie: when assigning onclick functionality)? I know I should, but I don’t fully understand why…
Example:
It’s my understanding that this:
$(callingImg)[0].setAttribute("onclick", "function(){removeChildren(this);}");
is better than this:
$(callingImg)[0].setAttribute("onclick", "removeChildren(this)");
One of the most common uses of function wrappers is to maintain or lock in that function’s context. For example, if you have some object and you want to use one of it’s method’s as the
onclickhandler for a given element:If
someObject.someMethodmakes any references tothis, instead ofthispointing tosomeObjectit will instead point tosomeElementbecause the context has changed. By wrapping thesomeObject.someMethodyou are still executing
someMethodas a method ofsomeObjectrather than as a method ofsomeElement.However, if the event handler method never makes any references to
this, then a wrapper isn’t needed.From the example code that you posted, if you just did
removeChildren(this)would be executed immediately and it’s return value would be assigned as theonclickhandler.Here’s some sample code to illustrate what’s happening
Output:
As a side note, it looks like you’re using jQuery. If that’s the case, you can simply do
better still, if there is always one
callingImgor you want to apply the same click handler to everycallingImg, you can just do