简体   繁体   中英

Javascript overloading functions

So I'm reading through a book and it uses this method to overload functions-

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

I have a few questions on this.

  1. Why is fn.length still in scope when the function that's passed in is called? Shouldn't executing the addMethod have caused fn to go out of scope?
  2. Why isn't the arguments referring to the arguments property of the anonymous function, rather than the arguments property of the fn function? (which it should I thought?)
  1. The parameter "fn" is in scope because that's how JavaScript works. It's part of the closure around that anonymous function.
  2. The anonymous function created is the replacement for the original function bound to the object with the property name "name". When called, it checks the arguments actually passed on that particular call by looking at the arguments object. If it sees that the number of arguments passed is the same as the number of formal parameters in the "fn" function, then it calls that function. Otherwise, it calls the previous ("old") function, if it exists and is a function.
    A key thing to understand is that the .length property of a function instance gives you the number of formal parameters in the declaration. For example, the .length for that "addMethod" function would be 3 .

The way that closures work in JavaScript took me a while to really "get" because I was a C programmer for a long time. In languages like that, space for the function call local variables (etc) is allocated on the stack, and when the function exits it's all popped off the stack. JavaScript just doesn't work that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM