奇怪的javascript函数行为(strange javascript function behavior)
这里是js忍者秘密的小例子:
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}`)我认为必须有这个功能
(a,b) => console.log(a, b)因为它之前是用ol写的
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
最满意答案
所有'旧'函数都保持存在,因为每次调用'addMethod'都会创建一个不同的变量'old' (只能在'addMethod'函数体分隔的范围内访问)
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)
更多推荐
发布评论