2

I am coming back to this book after unable to understand previous chapters(including concept of assert) but now that I am understanding this, I proceed and I was reading chapter 4 when I saw below example. I think part that doesn't make sense to me(even w/ the diagram in the book), why when ninja={} (which I assume then chirp inside of ninja is gone?), why samurai is still able to refer to that anonymous function as basically ninja.chirp?).

I totally get the fix for this.chirp to make it work but I really don't get this concept of why samurai is able to point to chirp which should no longer be available(or is this the closure that i am not fully understanding?

I get the normal closure where function returns and has access to lexical scope but this doesn't look that way.. )

var ninja = {
    chirp: function(n){
        return n > 1 ? ninja.chirp(n-1) + "-chirp" : "chirp";
     }
    };
    var samurai = { chrip: ninja.chirp };
    ninja = {};
    try {
         assert(samurai.chirp(3) == "chirp-chirp-chirp", "is this going to work?);
    }
user3502374
  • 781
  • 1
  • 4
  • 12

1 Answers1

2

Objects are "copy by reference" so when samurai is created, it has copied ninja. If you reset ninja after it was copied to samurai, then ninja still exists in the context of samurai.

If you were to move ninja = {}; above var samurai = { chrip: ninja.chirp }; then ninja in the context of samurai will be null.

Community
  • 1
  • 1
ZeroBased_IX
  • 2,667
  • 2
  • 25
  • 46
  • So when ninja was reset, object inside lives and since samurai was pointing at chirp by reference it can still point to it. Ok make sense. Now if nobody points to chirp , is that GC automatically? – user3502374 Dec 08 '15 at 19:48
  • Pretty much, since the way to access chirp has been removed, it cannot exist. – ZeroBased_IX Dec 08 '15 at 19:49