Devs love ZenUML
Devs love ZenUML

Reputation: 11892

Javascript variable lifecycle, will the variable be copied when it is returned?

It is hard to describe the situation without code. My modification made some answers irrelevant. I past the original code here and simplified version below:

function Entity(){
  var value = {};

  return {
    'value': value
  };
}

var e1 = Entity();
var e2 = Entity();
alert(e1.value === e2.value);

I thought it should return true. But in fact, it returns false. Is 'value' copied when it is returned from the function Entity?

update I think I know the reason now. each time Entity function is called the expression "var value={};" will generate a new Object. Thanks.

Upvotes: 0

Views: 608

Answers (3)

hugomg
hugomg

Reputation: 69954

value is not copied when its returned, but a new Object is created whenever you run the Entity function.

You can observe the "new Object" creation with simple code like

console.log({} === {}) //should give false

var a = {};
console.log(a === a); //should give true

And you can check that things don't get copyed on return by assigning to more variables when running your function

var a,b,c;

function Entity(){
   var value = {};
   a = value;
   b = value;
   return value;
}

c = Entity();

console.log(a==b, a==c, b==c); //should all give true

Upvotes: 1

plalx
plalx

Reputation: 43728

Your function is currently creating a new object each time it is getting called.

Keeping the same interface as in your example, to share the same array, you could do the following ->

Entity = (function () {
    //this variable is accessible only in the scope of this function
    var messageBoxes = ['hello'];

    //we return a function that return an object that will make the private messageBoxes variable accessible through it's messageBoxes property.
    return function () {
        return { messageBoxes: messageBoxes };
    };
})(); //note that this function will be self-executing


alert(Entity().messageBoxes === Entity().messageBoxes);

However, you would not be gaining anything here since you would be making the private messageBoxes variable publicly accessible directly.

Upvotes: 0

glebm
glebm

Reputation: 21100

[elements...] syntax creates a new array. In javascript, === operator compares arrays by reference (not by contents), so the result is false

Upvotes: 0

Related Questions