为什么以下代码只能在 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
。
幸运的是,修复非常简单。移动 util.inherits
调用之前将方法添加到 Child.prototype
。
以下代码适用于 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());
关于javascript - Node.js 中依赖于版本的类型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003949/