closures - Understanding this JavaScript function overloading example -
i'm studying secrets of javascript ninja john resig , i'm hoping can me further understand 1 of examples.
it function allows method overloading on object, each overload has it's own definition , behaviour. blogged here.
the code looks this:
function addmethod(object, name, fn) { var old = object[name]; object[name] = function(){ if (fn.length == arguments.length) return fn.apply(this, arguments) else if (typeof old == 'function') return old.apply(this, arguments); }; and used this:
addmethod(obj,'funcname',function(){}); addmethod(obj,'funcname',function(a){}); addmethod(obj,'funcname',function(a,b){}); i think understand of how works can better explanation can give blog post above).
however, accesses value of old , fn using closures, i'm still studying.
edit - added jsfiddle below.
when trying understand it, realised line return fn.apply(this, arguments) return fn() seems same result. see example in jsfiddle.
so, why using apply syntax if not required?
i have tried playing example in jsfiddle without apply , seems wo
also, happening when return functions, in case of:
return old.apply(this, arguments); i want solid understanding of not how use method why works insight appreciated.
thanks
so, why using
applysyntax if not required?
it required usage.
this , arguments different every function , set when they're called. using fn(), fn called empty arguments collection or no value passed this.
.apply(this, arguments) calls fn or old , passes along values both current function.
var obj = {}; addmethod(obj, 'funcname', function (a, b) { console.log(this === obj); console.log(a, b); console.log(arguments[0], arguments[1]); }); obj.funcname(2, 3); // true // 2, 3 // 2, 3 also, happening when return functions, in case of:
return old.apply(this, arguments);
well, purpose of addmethod create chain of functions each knows , can call old function created before it.
for example book, chain built as:
// after: addmethod(obj, 'funcname', function(){}); obj.funcname = function(){...} ──> function(){} // after: addmethod(obj, 'funcname', function(a){}); obj.funcname = function(){...} ──────> function(a){} └── function(){...} ──> function(){} // after: addmethod(obj, 'funcname', function(a,b){}); obj.funcname = function(){...} ──────────> function(a,b){} └── function(){...} ──────> function(a){} └── function(){...} ──> function(){} legend: `└──` represents `old` reference `──>` represents `fn` reference each function(){...} unique instance created reevaluating same expression in different scope/closure:
function(){ if (fn.length == arguments.length) return fn.apply(this, arguments) else if (typeof old == 'function') return old.apply(this, arguments); } each .apply() follows "arm" or "arrow" either old or fn , returns allow result passed through / in reverse.
Comments
Post a Comment