gpt4 book ai didi

javascript - 如果我在 javascript 中子类化时没有正确设置构造函数,会出现什么问题?

转载 作者:行者123 更新时间:2023-11-29 10:16:05 24 4
gpt4 key购买 nike

我最近在 javascript 中学习基于原型(prototype)的 OOP。在阅读了很多解释 javascript 原型(prototype)机制的网站后,我从 Mozilla 中选择了这种方法。

以下是 Mozilla 的一些片段:

// Shape - superclass
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();

rect instanceof Rectangle // true.
rect instanceof Shape // true.

rect.move(1, 1); // Outputs, "Shape moved."

我知道 Rectangle.prototype = Object.create(Shape.prototype); 会正确设置原型(prototype)链,这样 Rectangle 的实例就会继承 形状

但是 Rectangle.prototype.constructor = Rectangle; 行有点令人困惑。

来自 this website我知道当我们创建一个像 function MyClass(){} 这样的新对象时,javascript 会将它的原型(prototype)设置为一个空对象,而 MyClass.prototype.constructor 会指向后面到 MyClass。所以 Rectangle.prototype.constructor = Rectangle; 将修复损坏的链接,因为 Object.create(Shape.prototype).constructor 仍然指向 Shape .

但是如果我删除这一行,我仍然可以毫无问题地运行下面的代码。我只是很好奇构造函数属性是否有任何用例?如果我让它指向父类(super class)会出什么问题?

最佳答案

以这种方式设置属性将使其可枚举(for in 语句将列出构造函数属性)。

var rec = new Rectangle();
'constructor' in rec; //true

您应该使用 Object.defineProperty 或将第二个参数传递给 Object.create。

Rectangle.prototype = Object.create(Shape.prototype, {constructor: {enumerable: false }});

var rec = new Rectangle();
'constructor' in rec; //

有关构造函数属性的更多信息,请参阅此线程:

https://stackoverflow.com/a/4013295

关于javascript - 如果我在 javascript 中子类化时没有正确设置构造函数,会出现什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com