为什么Node.js要用ObjectSetPrototypeOf(A.prototype,B.prototype);和ObjectSetPrototypeOf(A,B)继承实现。

问题描述 投票:0回答:1

我发现Node.js是这样实现继承的,比如。https:/github.comnodejsnodeblobmasterlib_http_server.js。

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

而不是只设置prototype。

ObjectSetPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype);
node.js inheritance prototype
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。新玩具,我用下面的例子来说明这个概念(细节省略)。

class Color {
}
class ColorWithAlpha {
}

与此图一起展示了由该图创建的两条平行原型链,一条是构造函数本身,另一条是它们在用于创建对象时指定为原型的对象。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.