Reputation: 1177
I was learning about constructors, and I came across the new
keyword.
var obj = new myContructor();
I learnt that it created a new object, set its prototype as constructor.prototype
, set its properties as according with the this
keyword, and finally returns that object.
Now, I am confused as to where exactly does it create the new object, as inside memory or somewhere where it is volatile.
And what do we mean when saying it RETURNS that object, that it creates a copy of the new object at the location of the var obj, or does it reference obj to wherever it created the new object ?
Upvotes: 0
Views: 69
Reputation: 521995
There are many things going in behind the scenes in Javascript; things are constantly being created in memory that you do not have access to. As far as you are concerned with this while writing Javascript code:
new
creates an object and does all the prototype stuffmyConstructor()
is executed, and this
inside the function is set to that objectmyContructor
is called with the object as context)myConstructor
is done, the object is assigned to the variable obj
as result of all thisThere are a bunch of caveats regarding what myConstructor
can return and how that influences the result, but we'll ignore that for simplicity. The basic chain of events is new
creates object → myConstructor
sees that object as this
→ obj
"receives" this object as return value of new
.
Of course, all this creating of the object and passing it around to different places is done by the Javascript engine, and requires internal storage of the object somewhere in memory.
Upvotes: 1
Reputation: 943097
inside memory or somewhere where it is volatile
Yes, of course. Just like any other piece of data in the program.
do we mean when saying it RETURNS that object
You are making a function call. Function calls have return values. The object is the return value of that function call.
it creates a copy of the new object at the location of the var obj
It creates it in the function, then it returns a reference to it (just like any other object), and that reference is stored in the variable because you used an assignment.
Upvotes: 2