Executing a function in a JavaScript command template

I am currently reading in the fog addy Osmani JavaScript Design Patterns, which can be found here: http://addyosmani.com/resources/essentialjsdesignpatterns/book/ .

I find it quite enjoyable and very helpful. I have a question about one of the patterns in the book, namely the Command Pattern.

In the book, Addie explains that the command template helps separate objects and method calls a little better.

Here is my version of his example:

var person = { sayName: function (name) { return "My name is " + name; }, sayAge: function (age) { return "My age is " + age; }, sayGender: function (gender) { return "My gender is " + gender; } } person.execute = function (name) { return person[name] && person[name].apply(person, [].slice.call(arguments, 1)); } console.log(person.execute("sayName", "Sethen")); 

The magic is performed in the execution method. As you can see, you pass the method name and arguments, and the method takes care of everyone else.

My confusion stems from the fact that the execute method really returns. When you look at this, it looks like a short circuit with && , which I always considered logical due to JavaScript conversion.

However, if you try the code, it works exactly as it should by running My name is Sethen .

In addition, I found that just using return person[name].apply(person, [].slice.call(arguments, 1); gives the same results and, in my opinion, is much easier to read.

So my question is how return works in the original execute method:

 return person[name] && person[name].apply(person, [].slice.call(arguments, 1)); 

and how does the && operator work in this case to make it work?

+4
source share
2 answers

The && operator does not always return boolean . It returns the value of the last subexpression that it evaluates. If the name of the requested method exists, this expression will return the result of calling .apply() .

So:

 return person[name] && person[name].apply(person, [].slice.call(arguments, 1)); 

means:

 if (!person[name]) return person[name]; return person[name].apply(person, [].slice.call(arguments, 1)); 
+6
source

In this case, && acts as an if statement.

If you passed in what was not a method for this object, it would be false and would not continue the rest of the instruction.

+1
source

Source: https://habr.com/ru/post/1492359/


All Articles