当子类扩展超类时,为什么要重置对象构造函数?

Why do you reset an objects constructor when a subclass extends superclass?

问题:为什么当子类扩展超类时,示例将Rectangle.prototype.constructor设置回Rectangle?这是最佳做法吗?是为了说明它被重置了吗?因为这个例子无论如何都有效。

            function Shape() {
              this.x = 0;
              this.y = 0;
            }

            // superclass method
            Shape.prototype.move = function(x, y) {
              this.x += x;
              this.y += y;
              console.info('Shape moved.');
            };

            // Rectangle - subclass
            function Rectangle() {
              Shape.call(this); // call super constructor.
            }

            // subclass extends superclass

            Rectangle.prototype = Object.create(Shape.prototype);
            Rectangle.prototype.constructor = Rectangle;

            var rect = new Rectangle();
            console.log(rect);
            console.log('Is rect an instance of Rectangle? ' + (rect instanceof Rectangle)); // true
            console.log('Is rect an instance of Shape? ' + (rect instanceof Shape)); // true
            rect.move(1, 1); // Outputs, 'Shape moved.

当Rectangle.prototype = Object.create(Shape.prototype);是 运行,它将默认将 Rectangle 的构造函数设置为 Shape.prototype.constructor - 这不是您想要的。现在您必须继续并将 Rectangle.prototype.constructor 显式设置回 Rectangle 构造函数,因此任何新对象都将是 Rectangle 对象。将您的代码粘贴到此处:http://www.objectplayground.com/、select "classical inheritance",并将 "rect" 更改为“this.instance = new Rectangle();”。尝试一下,注释掉该行,看看它有什么不同。

希望这是有道理的!