简体   繁体   中英

Understanding a simple piece of JS code - Functions -

I am reading that Ninja Secrets of JS Book and seeing this part of example 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 an object ninja and it has a method.

I understand the second part that ok now we are creating a new object called samurai and it has a property called chirp .

The part that confuses me is ninja.chirp part of it, what are we doing here? How is it working?

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 being constructed.

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);

I have seen this example so many times, and it is a horrible example. For starters, named function expressions are buggy in IE, but aside from that they are completely unnecessary as you can simply reference arguments.callee .

That aside, using a recursive function to repeat a string is just asking for trouble. The whole thing could be made so much more simply:

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

In here, chirp its been copied to samurai . Than you can destroy the ninja object and still use the samurai.chirp method.

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