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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

the code is from a book, it's hard to contact the author. Thanks for your answer.
you said the author is avoiding a ReferenceError, but before it if(!fns){ return false; } had already checked fns whether was undefined
Hey, I never said the author was consistent or sane. That's definitely a question for the author.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.