0

This is the code:

var Event=(function(){
    var clientList={},listen,trigger,remove;
    listen=function(key,fn){
       /*some code*/
    };
    trigger:function(){
        var key=Array.prototype.shift.call(arguments);
        fns=clientList[key];
        if(!fns||fns.length==0){
            return false;
        }
        for(var i=0,fn;fn=fns[i++];){
            fn.apply(this,arguments);
        }
    };
    remove:function(key,fn){
        var fns=clientList[key];
        if(!fns){
            return false;
        }
        if(!fn){
            fns&&(fns.length=0)
        }else{
            for(var l=fns.length-1;l>=0;l--){
                var _fn=fns[l];
                if(_fn===fn){
                    fns.splice(1,1); 
                }
            }
        }

    };
     /*some code*/
})();

I could not understand why var key=Array.prototype.shift.call(arguments); instead of passing in arguments and fns&&(fns.length=0) instead of fns.length=0? I will highly appreciated if you could respond to my question.

1 Answers1

0

You might consider asking the author of this code rather than posing it as a question to random people on the Internet. However, here are my slightly educated guesses as to why the author chose the idioms she did:

  • Why var key=Array.prototype.shift.call(arguments); instead of passing in arguments?: She's not explicitly defining what arguments are coming in and being passed to the observing functions, so she can accept and pass along any arbitrary number of arguments. She's only requiring that the first argument be a key to which set of functions should be called. This is a form of Currying.
  • [Why] fns&&(fns.length=0) instead of fns.length=0: If fns was undefined or otherwise falsey, it would be bad to ask if it had a property. By checking if it's truthy before referencing a potential property, the author is avoiding a ReferenceError. This is a form of Short-circuit evaluation
Will
  • 2,163
  • 1
  • 22
  • 22
  • the code is from a book, it's hard to contact the author. Thanks for your answer. – 落叶无痕 Jul 27 '16 at 07:17
  • you said `the author is avoiding a ReferenceError`, but before it `if(!fns){ return false; }` had already checked fns whether was undefined – 落叶无痕 Jul 27 '16 at 07:31
  • Hey, I never said the author was consistent or sane. That's definitely a question for the author. – Will Jul 27 '16 at 14:36