Exemplary Paul Irland Duck Pattern

The question was about duck punching, which I first met on Paul Ireland’s blog. I get a general premise ... I keep a reference to an existing function, and then replace the existing function with a conditional branch, which will call a new function if the condition is met, or the old version if not. My question is: why should we use "apply" with 'this' as the first parameter when we call the _old function? I understand how to apply the work, but I'm looking for some clarification as to why this 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);
+5
source share
3 answers

Consider this example

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

obj.baz, , , ( ). , . .

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

, , , .

+8

this, apply() , this .

apply() , arguments, .

, , this, , this .

+1

apply, JavaScript , this to, - , , / .

Using apply, you make sure that the thiscorrect value is used for , for example. the one with which the wrapper function is called.

+1
source

All Articles