Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paul Irish 'duck punching' pattern observation

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);
like image 985
mike Avatar asked May 01 '11 14:05

mike


3 Answers

Consider this example

var obj = {
    foo: "bar",
    baz: function () {
        return this.foo;
    }
};
o = obj.baz;
obj.baz(); // "bar"
o(); // undefined

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.

var obj = {
    baz: function () {
        return this;
    }
};
o = obj.baz;
obj.baz() === obj; // true
o() === obj; // false
o() === window; // true

A proper context will likely be important for the .method to work as intended.

like image 96
Rafael Avatar answered Nov 19 '22 10:11

Rafael


You pass this because apply() needs the first argument to be what this should be when calling the old function.

apply() is being used so you can easily hand arguments which will be treated as the arguments to the old function.

So, when deciding what to pass as this, you have chosen to pass on what this is in that context.

like image 27
alex Avatar answered Nov 19 '22 09:11

alex


If you were to call the original function without apply, you let JavaScript decide what to bind this to, and that may well be something different from what it would be bound to if you hadn't monkeypatched/duckpunched the original code.

Using apply, you ensure that the correct value is used for this, e.g. the one the wrapper function is being called with.

like image 1
Martijn Pieters Avatar answered Nov 19 '22 10:11

Martijn Pieters