Does Object.defineProperty has access the memory address of object?

85 views Asked by At
var obj = {};
Object.defineProperty(obj, "name", {
  value: "john doe"
});
console.log(obj.name); // john doe

How Object.defineProperty assign new property to the object?!

We don't call it in a new variable, so how this will assign to the main object without return new?!

Does it use memory address of variable for assigning property?!

1

There are 1 answers

0
The Spooniest On

Yes, it does. It gets that address from obj when you pass it in. All of this happens behind the scenes.

Actually, the above statement isn't quite correct. According to the spec, what JavaScript gets is a thing called a reference to the object. Most implementations use memory addresses for references, but the spec doesn't require it, and some implementations do it differently. For example, the Narcissus engine is written in JavaScript, but JavaScript doesn't have access to memory addresses, so Narcissus has to implement references another way.

But the way that the engine implements references doesn't really matter. What matters is that this reference gets stored in obj behind the scenes. In a language like C or C++, you would have to dereference that in order to get to the data in the underlying object, but JavaScript does this for you automatically. That's why you don't hear references being talked about much in JavaScript; there's usually not much need to talk about them, because of the automatic handling. But they are there.