jack mulraney
jack mulraney

Reputation: 77

What is prototype.constructor for?

In continuation of this question, what is prototype.constructor for?

I thought that by simply doing:

new some_object()

that the function object became a constructor. I don't understand why you would need to set it in this manner.

some_object.prototype.constructor = some_object;

Upvotes: 3

Views: 230

Answers (2)

apsillers
apsillers

Reputation: 116040

Imagine a function that takes an object and constructs a new instance of that object's type:

function makeNewObjectWithSameType(typedObject) {
    return new typedObject.constructor();
}

There is why you might need a constructor property.

But constructor is already set when you define your constructor -- why would you need to define it again? Consider the following case:

function Foo() {
    // constructor logic...
}
Foo.prototype.constructor == Foo; // true by default

var f = new Foo();
f.constructor == Foo; // true!

But now consider that Foo.prototype is overwritten:

function Foo() {
    // constructor logic...
}
Foo.prototype = {
    // new prototype; this is an `Object`
}
Foo.prototype.constructor == Foo; // FALSE! Foo.prototype is an Object
// thus, constructor == Object

var f = new Foo();
f.constructor == Foo; // FALSE! again, this is Object

If you passed in f to my makeNewObjectWithSameType function above, it would construct an Object, rather than a Foo.

You can solve this by manually resetting Foo.prototype.constructor = Foo; after you reassign Foo.prototype to a new object.

Upvotes: 1

vbo
vbo

Reputation: 13593

Suppose class A inherit B using the following:

A.prototype = new B();

After this A.prototype.constructor == B. So instances of A have a constructor from B. It's a good practice to reset a constructor after the assignment.

Upvotes: 1

Related Questions