Understanding the Simple Part of JS Code - Functions -

I read that Ninja Secrets of JS Book and see this part of the sample code:

var ninja = { chirp: function signal(n) { //#1 return n > 1 ? signal(n - 1) + "-chirp" : "chirp"; } }; var samurai = { chirp: ninja.chirp }; ninja = {}; 

So, I understand the first part: we have a ninja object, and it has a method.

I understand the second part, which now approves a new object called samurai and has the chirp property.

The part that bothers me is ninja.chirp its part, what are we doing here? How it works?

+4
source share
3 answers

It takes the value of the chirp property of the ninja object (which is a function) and assigns it to the chirp property of the object that is being created.

Here is a simpler example (using a string instead of a function):

 var foo, bar; foo = { "an": "object" }; bar = { "an": foo.an } alert(foo.an); alert(bar.an); 
+5
source

I have seen this example many times and it is a terrible example. Firstly, named functional expressions are erroneous in IE, but beyond that they are completely unnecessary, as you can just refer to arguments.callee .

Aside, using a recursive function to repeat a line, you just ask for problems. All this can be done much easier:

 function signal(n) { return new Array(n+1).join("-chirp").substr(1); } 
+2
source

Here chirp he was copied to samurai . Than you can destroy the ninja object and still use the samurai.chirp method.

+1
source

All Articles