2016-08-03 103 views
0

这里是JS忍者的秘密小例子:奇怪的javascript函数的行为

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); 

,我不明白为什么在这个变量

const old = obj[methodName]; 

的工作,因为这功能

a => console.log(`one: ${a}`) 

我认为必须有这个func

(a,b) => console.log(a, b) 

,因为它是在醇写入前

回答

1

所有的“老字号”的功能保持因为每次调用'addMethod'都会创建一个不同的变量'old'(它只能在由'addMethod'函数体定义的范围中访问)

+0

得到它,谢谢。这种行为对我来说很不寻常 –

0

你的addMethod功能设置obj[methodName]

function() { 
    if (fn.length === arguments.length) { 
     return fn.apply(this, arguments); 
    } else if (typeof old === 'function') { 
     return old.apply(this, arguments); 
    } 
} 

这就是你....

+0

是的,我知道。我的意思是为什么这个'ninja.whatever(2,2);'不是覆盖变量老 –