2016-08-03 95 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);'不是覆蓋變量老 –