Had a question about the ‘duck punching’ pattern I first encountered on Paul Irish’s blog. I get the general premise… save a ref to an existing function, then replace the existing function with a conditional branch that will call a new function if condition is met, or the old version if not. My question is why do we have to use the “apply” with ‘this’ as the first param when we call the _old function? I understand how apply works, but I’m looking for some clarification on why it is necessary.
(function($){
// store original reference to the method
var _old = $.fn.method;
$.fn.method = function(arg1,arg2){
if ( ... condition ... ) {
return ....
} else { // do the default
return _old.apply(this,arguments);
}
};
})(jQuery);
Consider this example
if you call a method with obj.baz, the object that is behind the dot is the function’s context (this will refer to this object).
if you store a method in a variable, you lose the information about the context. In that case, the context will be set to the global object.
A proper context will likely be important for the .method to work as intended.