Devashish Devashish - 1 year ago 59
Javascript Question

Why the `constructor` points to Object in the following?

I read that whenever an object literal is defined, the Object constructor is not called:

var ob1 = new Object(); // constructor called
var ob2 = {}; // constructor never called

Now consider the following:

// a constructor
function Animal (name, food) {
// definition of constructor

Animal.prototype = {
// some properties in the prototype
// but `constructor` is not set back to Animal

In the above code, because I am completely overwriting the prototype, the
is set to point to
. If I am not wrong, the constructor property is set to point to the constructor which when called, causes the prototype to be created. My question is, although I am redefining the prototype completely, the Object constructor isn't called (because it is just an object literal). Then why the
points to object.

Answer Source

why the constructor points to object.

The property and its value are being inherited from Object.prototype.

Animal.prototype.constructor === Object.prototype.constructor; // true

Since Animal.prototype is an Object instance, created from the literal/initializer, it inherits all properties from Object.prototype, including its constructor.

The constructor property is typically assigned on a prototype object and inherited by instances.

The engine sets up that much for you, but only once when a new function is defined.

function Animal() {}

console.log(Animal.prototype.constructor); // function Animal() {}

That automatic assignment isn't kept when you replace the prototype entirely.

Animal.prototype = {};

console.log(Animal.prototype.constructor); // function Object() {}

The constructor property is also just informational. It doesn't actually offer a guarantee of its accuracy, as you've found, since it can easily be altered or overridden.

And, invoking a constructor function won't automatically assign the constructor property's value for the new instance. At least, unless you define the function to do that explicitly:

function Animal() {
    this.constructor = Animal;

Animal.prototype = {};

console.log(new Animal().constructor); // function Animal() { ... }

Otherwise, since the modified Animal.prototype doesn't specifying its own constructor...

Animal.prototype.hasOwnProperty('constructor'); // false

It inherits that value from its own prototype:

Object.getPrototypeOf(Animal.prototype) === Object.prototype; // true

Object.prototype.hasOwnProperty('constructor'); // true

Object.prototype.constructor; // function Object() { }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download