What objects are there in memory in this JavaScript?

Given the following code, what custom objects are in memory after line 1 and after line 2?

function MyCtor() {}

//At this point a single user-defined object exists, the constructor function `MyCtor`

var v = new MyCtor();

//Here in addition to the constructor function defined above we have `v` (a `MyCtor` instance) and another instance of `MyCtor` acting as `v.__proto__`. So that is 3 objects in total.

      

+3


source to share


1 answer


There are two objects after the first line. There is a function object and there is a prototype object for that function.

(Well, the function is already created when the code is parsed, so the objects exist before the code even starts executing. It would be more accurate to say that the first line causes two objects to exist.)

After the second line, there is another object - an object instance. An __proto__

object property does not contain another object instance, it is a reference to the prototype object of the constructor function.

Example:



function MyCtor() {}

console.log(MyCtor.prototype);

var v = new MyCtor();

console.log(v.__proto__);
console.log(MyCtor.prototype === v.__proto__);

      

Output:

MyCtor { }
MyCtor { }
true

      

Demo: http://jsfiddle.net/323bg/

+4


source







All Articles