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.prototype
从Parent.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
- Node.Js + Expressjs中的inheritance
- 在这种情况下使用Javascript的原型inheritance有什么好处吗?
- Javascriptinheritance对象覆盖其他inheritance对象
- 为什么我们应该使用Object.create?
- 水线ORM的inheritance
- 为什么console.log()不显示Object.create的inheritance属性?
- 节点js原型对象'self'var不存储正确的callback上下文
- 在这种情况下实现JavaScript的inheritance
- 使用Node.js,Handlebars和Express进行模板inheritance