inheritance函数如何在Node.js中工作?

这是node.js中的inheritance函数:

exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; 

有人可以给我这个function的“大图”吗? 我不是100%确定我得到Object.create,而且…我很困惑!

任何帮助/指针将不胜感激…

芝加哥商业交易所。

 var Parent = function () { this.isParent = true; }; Parent.prototype.doSomething = function () { return 42; }; var Child = function () { this.isChild = true; } util.inherits(Child, Parent); var c = new Child; console.log(c.isChild); console.log(c.doSomething()); 

它只是确保Child.prototypeParent.prototype正确inheritance。 它还将constructor属性Child.prototype设置为正确的值。

请确保在您的Child声明后直接调用util.inherits

现在有两个版本的inheritance函数。 Pre node.js版本5.0.0使用Object.create和post(包含)v5.0.0使用Object.setPrototypeOf。

在Object.create版本中,superCtor的原型被设置为ctor.prototype的原型。 但是,在这个过程中,ctor.prototype上的任何方法/属性都将被删除。 这是一个工作的例子;

 var inherits = function (ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; function Manager(managerName) { this.managerName = managerName; } Manager.prototype.getManagerName = function () { return this.managerName; } function Team(managerName, teamName) { this.teamName = teamName; Team.super_.apply(this, arguments); } Team.prototype.getTeamDetails = function () { return this.teamName + ' is managed by ' + this.managerName; } inherits(Team, Manager); var obj = new Team('Klopp', 'LiverpoolFC'); console.log(obj.getTeamDetails()); //obj.getTeamDetails is not a function