I’m currently going through Stoyan Stefanov’s book “Object-oriented JavaScript” and I’ve stumbled on an interesting problem. Here’s the code:
var shape = {
type: 'shape',
getType: function() {
return this.type;
}
};
function Triangle(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
this.type = 'triangle';
}
Triangle.prototype = shape; // changing the prototype object
Triangle.prototype.getPerimeter = function() {
return this.a + this.b + this.c;
}
var t = new Triangle(1, 2, 3);
t.constructor; // logs Object() instead of Triangle(a, b, c)
As you can see, here is a simple example of the constructor inhereting some properties from the prototype object. But the constructor property of object t points to the Object() object instead of Triangle(a, b, c), as it should have. If I comment the line with the prototype change, though, everything works fine. What’s my problem?
(Reread the whole prototype chapter in Object-oriented Javascript and JavaScript Patterns, couldn’t find an answer).
P.S. Sorry for my bad English, trying to practice it. 🙂
I will explain your code in two parts. Firstly, what is the
constructorproperty actually? Secondly, why doesn’t it returnObjectsin your code?The
constructorproperty and Stoyan’s mistake:In Stoyan Stefanov’s book, p150, he states:
It is wrong. According to the JavaScript Definitive Guide Section 9.2
You can test it with
Triangle.prototype.constructor. It has been set when the function is defined.Conclusion 1: the
constructoris in fact the property ofConstructor.prototype. In your case, it isTriangle.prototype.constructor.All the instances of
Trianglecould access this property through the prototype chain. But these objects themselves don’t have theconstructorproperty. The following code proves it:Conclusion 2: when you access the
constructorproperty of an instance, you get them from the prototype chain.Why is it not working as you expected
You set
Triangle.prototypetoshapewhich doesn’t contain the originalconstructorproperty.Thus, this time, when you query
t.constructor, it will resolve it in the following process:constructort.__proto__, which isTriangle.prototype. You have set it toshapewhich doesn’t contain theconstructorproperty.t.__proto__.__proto__. It isTriangle.prototype.__proto__, and it is resolved asObject.prototype.Object.prototypehas theconstructorproperty and it refers toObject.