Problems with changing the prototype constructor

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; // 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 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. :)

+3
source share
5

. -, constructor ? -, Objects ?

constructor :

, p150, :

prototype - , , . - .

. JavaScript. 9.2

prototype - . -, .

Triangle.prototype.constructor. , .

1: constructor Constructor.prototype. Triangle.prototype.constructor.

Triangle . constructor. :

function Triangle(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.type = 'triangle';
}
var t = new Triangle(1, 2, 3);
t.hasOwnProperty('constructor');
>>false
t.__proto__.hasOwnProperty('constructor');
>>true

2: constructor .

,

Triangle.prototype shape, constructor.

, , t.constructor, :

  • constructor
  • t.__proto__, Triangle.prototype. shape, constructor.
  • - t.__proto__.__proto__. Triangle.prototype.__proto__, Object.prototype. Object.prototype constructor Object.
+6

"constructor", , . , .

- Mozilla.

+3

shape - , :

Triangle.prototype = shape;

Triangle Object

+1

native/class . Javascript ( ), new, .

:

Triangle.prototype = shape;

. Triangle.prototype.

:

t.constructor;

, , .

+1

shape , . - Object.

,

Triangle.prototype = ;

and Triangle.prototype.constructor = Triangle to override the newly set shape.prototype.constructor.

0
source

All Articles