1

我发现Node.js是这样实现继承的,例如: https ://github.com/nodejs/node/blob/master/lib/_http_server.js

ObjectSetPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype);   // line 174
ObjectSetPrototypeOf(ServerResponse, OutgoingMessage);  // line 175

而不是只设置原型:

ObjectSetPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype);
4

1 回答 1

0

这样父类的静态方法就被子类继承了,因为它们把父类的构造函数变成了子类构造函数的原型。

本机class语法做同样的事情:

class Parent {
    static example() {
        console.log("Parent.example");
    }
}

class Child extends Parent {
}

console.log(Child.example());                 // "Parent.example"
console.log(Child.hasOwnProperty("example")); // false
console.log("example" in Child);              // true, because it's inherited
console.log(Object.getPrototypeOf(Child) === Parent); // true

请记住,函数是对象。对象可以有原型。对象从其原型继承属性。在上面的示例中,Child(函数对象)以Parent(函数对象)为原型,因此它继承了example属性。在 ES5 之前,使用 JavaScript 代码创建的函数始终具有Function.prototype原型,但从 ES2015 开始,这并不总是正确的。class语法使超类构造函数成为子类构造函数的原型。您还可以在创建函数后通过 更改函数的原型Object.setPrototypeOf,但通常最好避免更改现有对象的原型。

在我的新书JavaScript: The New Toys的第 4 章中,我使用下面的例子来说明这个概念(细节省略):

class Color {
}
class ColorWithAlpha {
}

与此图一起显示由它创建的两个并行原型链,一个用于构造函数本身,另一个用于它们在用于创建对象时分配为原型的对象:

在此处输入图像描述

于 2020-05-03T10:56:04.997 回答