Litvinenko Evgeny
Litvinenko Evgeny

Reputation: 95

strange javascript function behavior

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

Upvotes: -1

Views: 53

Answers (2)

bedane
bedane

Reputation: 1127

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)

Upvotes: 0

Seti
Seti

Reputation: 2314

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....

Upvotes: -1

Related Questions