I am currently browsing Stoyan Stefanov’s book, Object-Oriented JavaScript, and I came across an interesting problem. Here is 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;
Triangle.prototype.getPerimeter = function() {
return this.a + this.b + this.c;
}
var t = new Triangle(1, 2, 3);
t.constructor;
As you can see, here is a simple example of a constructor that can infer some properties from a prototype object. But the constructor property of the object t points to the Object () object instead of the triangle (a, b, c), as it should be. If I comment on the line with the prototype change, everything works fine. What is my problem? (Reread the entire prototype chapter in object-oriented Javascript and JavaScript templates, could not find the answer). PS Sorry for my bad English, trying to practice. :)
source
share