-1

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

2 Answers 2

0

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

-1

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

yes, i know. I mean why this ninja.whatever(2, 2); isn't override variable old

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.