奇怪的javascript函数行为(strange javascript function behavior)

编程入门 行业动态 更新时间:2024-10-22 22:57:22
奇怪的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)

更多推荐

本文发布于:2023-08-07 03:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461231.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   奇怪   javascript   behavior   strange

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!