javascript - 关于函数重载的问题
黄舟
黄舟 2017-04-11 09:41:25
0
1
406

在《javascript忍者秘籍》上看到一段代码,用于函数重载。

function addMethod(object, name, fn) {
  var old = object[name];                        //#1
  object[name] = function(){
    if (fn.length == arguments.length)           //#2
      return fn.apply(this, arguments)           //#2
    else if (typeof old == 'function')           //#3
      return old.apply(this, arguments);         //#3
  };
}

示例是这样的:

var ninja = {};
addMethod(ninja,'whatever',function(){/*do something*/});
addMethod(ninja,'whatever',function(a){/*do something else*/});
addMethod(ninja,'whatever',function(a,b){/*yet something else*/});

但是有点看不懂addMethod方法,疑问如下:

  • if (fn.length == arguments.length)这个arguments是谁的arugments?调用addMethod时的?还是object[name] = function()这个匿名函数?

菜鸟一枚,若拍砖请轻拍

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
PHPzhong

你只需要加两句话做个试验就清楚了

function addMethod(object, name, fn) {
    var _addMethodArguments = arguments;
    var old = object[name];                        //#1
    object[name] = function() {
        console.log("is arguments of addMethod():", _addMethodArguments === arguments);
        if (fn.length == arguments.length)           //#2
            return fn.apply(this, arguments);           //#2
        else if (typeof old == "function")           //#3
            return old.apply(this, arguments);         //#3
    };
}


var ninja = {};
addMethod(ninja, "whatever", function() {/*do something*/ });

ninja.whatever();

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template