Trying to bend by head around Javascript's take on OO...and, like many others, running into confusion about the constructor
property. In particular, the significance of the constructor
property, as I can't seem to make it have any effect. E.g.:
function Foo(age) {
this.age = age;
}
function Bar() {
Foo.call(this, 42);
this.name = "baz";
}
Bar.prototype = Object.create(Foo.prototype);
var b = new Bar;
alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name); // "baz". Shows that Bar() was called as constructor.
alert(b.age); // "42", inherited from `Foo`.
In the above example, the object b
seems to have had the right constructor called (Bar
) – and it inherits the age property from Foo
. So why do many people suggest this as a necessary step:
Bar.prototype.constructor = Bar;
Clearly, the right Bar
constructor was called when constructing b
, so what impact does this prototype property have? I am curious to know what practical difference it actually makes to have the constructor property set 'correctly'—as I can't see it having any affect on which constructor is actually called after an object is created.
September 2020 Update
The answer below is from the days of ECMAScript 3 and the first sentence is no longer true because since ECMAScript 6, the constructor
property is used in a few places. However, I think the overall gist still applies. Thanks to T. J. Crowder for pointing that out in the comments, and please read his answer for a fuller picture of the current situation.
Original answer
The constructor
property makes absolutely no practical difference to anything internally. It's only any use if your code explicitly uses it. For example, you may decide you need each of your objects to have a reference to the actual constructor function that created it; if so, you'll need to set the constructor
property explicitly when you set up inheritance by assigning an object to a constructor function's prototype
property, as in your example.