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

标签 javascript node.js

为什么以下代码只能在 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/

相关文章:

javascript - 如何通过函数更新全局变量

javascript - WebdriverJS 是原始 selenium webdriver 的全功能替代品吗

javascript - rails 4 : setting link destination in CoffeeScript function

javascript - NG-Repeat 和 ng-table 问题

javascript - 无法以 redux 方式呈现我的 react 组件

javascript - JavaScript 中的 xml 到 json

javascript - 如何从 vkontakte 获取长期访问 token ?

javascript - Electron :X不是函数>>>(使用ipcrenderer/ipcmain进行回调)

javascript - backbone.js 上下文中的依赖注入(inject)

javascript - Karma/Jasmine 在没有运行测试的情况下超时