I am wondering, when that data has been added, will that data exist twice in memory or do newObj.data and data simply point to the same address in memory?
The latter. What's held in newObj.data
and data
is something called an object reference, not the object itself. The object is elsewhere in memory (just once); the reference is a value telling the JavaScript engine where the object is.
That's assuming that you ever actually call newObj.setData(data)
. Just the Object.create
itself doesn't set the data
property on the newObj
.
Let's throw some ASCII-art at it. After you do this:
let data = {text: 'a text'};
let newObj = Object.create({
setData(argData) {
this.data = argData;
}
});
...you have something like this in memory (various details omitted):
+−−−−−−−−−−−−−−−−+
data:[Ref54611]−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−>| (object) |
+−−−−−−−−−−−−−−−−+
| [[Prototype]] |−−+
| text: 'a text' | |
+−−−−−−−−−−−−−−−−+ |
|
+−−−−−−−−−−−−−−−−+ +−>(Object.prototype)
newObj:[Ref74135]−−−>| (object) | |
+−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−−−−−+ |
| [[Prototype]] |−−−>| (object) | |
| text: 'a text' | +−−−−−−−−−−−−−−−−−−−−+ |
+−−−−−−−−−−−−−−−−+ | [[Prototype]] |−−+
| setData:[Ref55462] |−−−−>(function)
+−−−−−−−−−−−−−−−−−−−−+
Then after:
newObj.setData(data);
...you have something like:
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| |
\ +−−−−−−−−−−−−−−−−+ |
data:[Ref54611]−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+−−>| (object) | |
+−−−−−−−−−−−−−−−−+ |
| [[Prototype]] |−−+ |
| text: 'a text' | | |
+−−−−−−−−−−−−−−−−+ | |
\ |
+−−−−−−−−−−−−−−−−−−+ +−>(Object.prototype) |
newObj:[Ref74135]−−−>| (object) | / |
+−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−−−−−+ | |
| [[Prototype]] |−−−>| (object) | | |
| text: 'a text' | +−−−−−−−−−−−−−−−−−−−−+ | |
| data: [Ref54611] |−−+ | [[Prototype]] |−−+ |
+−−−−−−−−−−−−−−−−−−+ | | setData:[Ref55462] |−−−−>(function) |
| +−−−−−−−−−−−−−−−−−−−−+ |
| |
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
Note that the conceptual value "[Ref54611]" is in both data
(the variable) and newObj.data
(the property). You never actually see the value of an object reference in code, but you can think of them as numbers telling the engine where the object is.