Maximus Maximus - 4 months ago 21
Javascript Question

MDN constructor property explanation confusion

I'm reading this article about

constructor
property and it states the following:


Returns a reference to the Object function that created the instance's
prototype.


And they give an example:

function Tree(name) {
this.name = name;
}

var theTree = new Tree('Redwood');
console.log('theTree.constructor is ' + theTree.constructor);


Here the instance is
theTree
and its prototype is
Object.getPrototypeOf(theTree)
, which is Object function, not
Tree
. What am I misunderstanding?

Answer

The prototype of an object is typically inherited from its constructor function:

function Tree() {}
Tree.prototype.foo = function () {};

var theTree = new Tree();

theTree now has theTree.foo from its prototype chain. The function Tree initialised the object, and is also responsible for the contents of its prototype chain. That's why they express it as "the Object function that created the instance's prototype".