Node.js中依赖于版本的类型继承

Version-dependent type inheritance in Node.js

本文关键字:类型 继承 版本 依赖于 js Node      更新时间:2023-09-26

为什么下面的代码只在Node.js 5.x和6.x下工作,而在4.x和更早的版本中中断?

有没有一种方法可以修改它,使其在任何Node.js 0.10.x-6.x中工作?

'use strict';
var util = require('util');
function Parent() {
}
Parent.prototype.show = function () {
    return this.msg(); // virtual-like call;
};
function Child() {
}
Child.prototype.msg = function () {
    return 'Hello!';
};
util.inherits(Child, Parent);
var test = new Child();
console.log(test.show());

在Node.js 5.x和6.x中,它显示Hello!。在Node.js的任何早期版本中,它都显示TypeError: this.msg is not a function

在Node 5.0之前,util.inherits使用Object.create()创建继承链。不幸的是,这有一个错误。在使用util.inherits之前附加到Child.prototype的任何内容都被删除了——这就是导致错误的原因。从5.0及更高版本开始,Node在后台使用Object.setPrototypeOf

幸运的是,修复非常简单。在将方法添加到Child.prototype之前移动util.inherits调用

以下代码将在0.10到6.0之间工作。

'use strict';
var util = require('util');
function Parent() {
}
Parent.prototype.show = function () {
  return this.msg(); // virtual-like call;
};
function Child() {
}
util.inherits(Child, Parent);
Child.prototype.msg = function () {
  return 'Hello!';
};
var test = new Child();
console.log(test.show());

通过查看两个不同版本的代码,我发现它们之间唯一的区别是实现原型继承的方式。

4.x

ctor.prototype=对象.create(superCtor.prototype{构造函数:{值:ctor,可枚举:false,可写:true,可配置:true}});

其中ctor是子构造函数,superCtor是父构造函数。

Object.setPrototypeOf(ctor.prototype,superCtor.prototype);

其中ctor是子构造函数,superCtor是父构造函数。


对于4.x版本(以及可能更低的版本),父的原型被分配给子的原型,因此完全取代了它

然而,最新版本使用了Object.setPrototypeOf,我假设它不会取代孩子的原型,而是保留了孩子的原型和父母的原型。

更新:我在ECMAScript 2017规范中发现了这一点,如果它有任何帮助的话。。。