这里是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)
,因为它是在醇写入前
得到它,谢谢。这种行为对我来说很不寻常 –