Frage

I have function that returns an object:

function makeObject() {
  return { 
    property: "value"
  };
}

I make can new object from it like this:

var newObject = makeObject();

I have some questions about this:

  1. Does newObject reference the original object that was returned by the function, or is it a completely fresh, new object with it's own properties?

  2. If it's a completely new object, is it then, in a sense, a deep copy of the object returned by the function?

  3. What happened to the original object in the function? If it's not possible to reference it, is it being kept alive in the JavaScript runtime?

War es hilfreich?

Lösung

  1. Yes (a new object is created each time you run the function, but a reference to that new object is returned by the function). You only ever store references to objects in JS variables.
  2. It isn't.
  3. The reference to it inside the function goes away. The reference to it that you returned is still available since you assigned it to a variable. Since there is still an accessible reference to it, it continues to exist.

The MDN documentation on garbage collection is useful related reading.

Andere Tipps

Here is an equivalent function:

function makeObj() {
  var o = new Object();
  o.property = 'value';
  return o;
}

The object literal syntax is, effectively, a shorthand for the above.

So yes, it's a completely new object, and no, it's not a deep copy, becuase there's nothing to copy. It's manufacturing a new object every time you call the function.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top