Sunday, November 3, 2019

Need to understand Javascript object references




I am looking at this piece of code from John Resig's website. What I don't understand is when the ninja object is set to an empty object, the yell method is still available to samurai.



Is it because since there is still a reference lying around to ninja, it wasn't garbage collected?



var ninja = {
yell: function(n){
return n > 0 ? yell(n-1) + "a" : "hiy";
}

};


var samurai = { yell: ninja.yell };

ninja = {};

console.log(samurai.yell(2)); //hiy



http://ejohn.org/apps/learn/#14 (Original source, I modified it a little to remove the named function expression).


Answer



In the following code:



var ninja = {
yell: function(n){
return n > 0 ? yell(n-1) + "a" : "hiy";
}
};



The value of ninja.yell is a reference to a function. The assignment:



var samurai = { yell: ninja.yell };


Assigns a value to samurai.yell that is a reference to the same function (i.e. the one referenced by ninja.yell). Then:



ninja = {};



Assigns a value to ninja that is a new, empty object. It has no effect on the value assigned to samurai.yell, which still references the function.



Variables have a value, values have a Type. There is a special Type called the Reference Type that is "…used to explain the behaviour of such operators as delete, typeof, and the assignment operators". So when an object is in an assignment expression, the value assigned is Type Reference.



Hence the variable still has a value, but it's value is a reference.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...