簡體   English   中英

奇怪的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寫的

所有的“舊”函數都保持存在,因為每次對“ addMethod”的調用都會創建一個不同的變量“ old” (只能在由“ addMethod”函數主體界定的范圍內訪問)

您的addMethod函數將obj[methodName]設置為

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

你得到的是...。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM