here is little example from secrets of js ninja:
function addMethod(obj, methodName, fn) {
const old = obj[methodName];
obj[methodName] = function () {
if (fn.length === arguments.length) {
return fn.apply(this, arguments);
} else if (typeof old === 'function') {
return old.apply(this, arguments);
}
};
}
let ninja = {};
addMethod(ninja, 'whatever', a => console.log(`one: ${a}`));
ninja.whatever(1);
addMethod(ninja, 'whatever', (a,b) => console.log(a, b));
ninja.whatever(2, 2);
addMethod(ninja, 'whatever', (a,b, c) => console.log(a, b, c));
ninja.whatever(3);
console.log(ninja);
console.dir(addMethod);
and i can't understand why in this variable
const old = obj[methodName];
work as this function
a => console.log(`one: ${a}`)
i think there is must be this func
(a,b) => console.log(a, b)
because it was write in ol before
asked Aug 3, 2016 at 9:14
Litvinenko Evgeny
951 silver badge10 bronze badges
2 Answers 2
All the 'old' functions keep on existing because each call to 'addMethod' creates a distinct variable 'old' (which is only accessible in the scope delimited by the 'addMethod' function body)
Sign up to request clarification or add additional context in comments.
Comments
Your's addMethod functions sets obj[methodName] to be
function () {
if (fn.length === arguments.length) {
return fn.apply(this, arguments);
} else if (typeof old === 'function') {
return old.apply(this, arguments);
}
}
Which is what you get....
1 Comment
Litvinenko Evgeny
yes, i know. I mean why this
ninja.whatever(2, 2); isn't override variable oldlang-js