An Object Null And { } Behaviour In Javascript
Solution 1:
This has nothing to do with the difference between null
and {}
, it depends only on how the ninja.yell
function is defined.
The first example doesn't work because inside the ninja.yell
function, you are referring to ninja
again:
return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
So, if later on your are assigning null
to ninja
, this code will throw an error because null
doesn't have a property yell
.
The second example works because that's what you are exactly not doing. Instead of referring to the object that holds the function (ninja
), you are giving the function a name and directly refer to that name:
function yell(n){
return n > 0 ? yell(n-1) + "a" : "hiy";
}
The function is basically "self-contained", it doesn't depend on the values of free variables.
Solution 2:
variables are references. so in the first one, yes, ninja.yell already assigned before ninja=null, but samurai.yell is a reference to ninja.yell - it is pointing to ninja.yell.
if you then later set ninja to null, samurai.yell, which is pointing to ninja, will also be null
Solution 3:
Have a look at this. It may help you out (the title of the question is not accurate though): Allocate memory in JavaScript
Post a Comment for "An Object Null And { } Behaviour In Javascript"