Javascript inherits函数在Node.js中是如何工作的?
这是node.js中的inherits函数:Javascript inherits函数在Node.js中是如何工作的?,javascript,inheritance,node.js,Javascript,Inheritance,Node.js,这是node.js中的inherits函数: exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, con
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
谁能告诉我这个函数是如何工作的?
我不是100%确定我得到Object.create,并且。。。我很困惑
如有任何帮助/建议,将不胜感激
美塞苔丝
它只是确保Child.prototype
正确地继承自Parent.prototype
。它还将构造函数属性子.prototype
设置为正确的值
确保在您的子声明之后直接调用util.inherits
。现在有两个版本的inherits函数。Pre-node.js版本5.0.0使用Object.create,post(含)版本5.0.0使用Object.setPrototypeOf
在Object.create版本中,Supercor的原型设置为ctor.prototype的原型。但是,在此过程中,将删除ctor.prototype上可用的任何方法/属性。下面是一个工作示例
var inherits=函数(ctor,supercor){
ctor.super=超级电机;
ctor.prototype=Object.create(supercor.prototype{
建造商:{
值:ctor,
可枚举:false,
可写:对,
可配置:true
}
});
};
职能经理(经理姓名){
this.managerName=managerName;
}
Manager.prototype.getManagerName=函数(){
把这个还给我;
}
职能团队(经理姓名、团队名称){
this.teamName=团队名称;
Team.super_.apply(这个,参数);
}
Team.prototype.getTeamDetails=函数(){
return this.teamName+由“+this.managerName”管理;
}
继承(团队、经理);
var obj=新球队(“Klopp”、“LiverpoolFC”);
log(obj.getTeamDetails())//obj.getTeamDetails不是一个函数
不确定它值多少钱,但是。。。好的,谢谢你。我正在重新阅读我的问题——以及答案——过了一会儿,当我最终“理解”了所有这些,我不得不说,现在一切看起来都非常简单。。。我想是时候离开这里去帮助别人了!
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());