javascript util.inherits在调用派生类函数时出现问题
我有下面的代码,其中有两个函数a、c和c继承自ajavascript util.inherits在调用派生类函数时出现问题,javascript,inheritance,Javascript,Inheritance,我有下面的代码,其中有两个函数a、c和c继承自a function a(){ console.log("constructor-a"); } a.prototype.fun1 = function(){ console.log("a-fun1"); } a.prototype.fun2 = function(){ console.log("a-fun2"); } function c(){ c.super_.call(this) console.lo
function a(){
console.log("constructor-a");
}
a.prototype.fun1 = function(){
console.log("a-fun1");
}
a.prototype.fun2 = function(){
console.log("a-fun2");
}
function c(){
c.super_.call(this)
console.log("constructor-c");
}
c.prototype.fun5 = function(){
console.log("c-fun1");
}
c.prototype.fun6 = function(){
console.log("c-fun2");
}
util.inherits(c,a);
var X = new c();
console.log("X instanceof a", X instanceof a);
console.log("X instanceof a", X instanceof c);
由于c是从a继承的,因此c和a的函数都应该可以从c的对象执行,但是,在这种情况下,输出如下:
X.fun1() --> a-fun1
X.fun2() --> a-fun2
X.fun5() --> TypeError: X.fun5 is not a function
X.fun6() --> TypeError: X.fun6 is not a function
先执行util.继承(c,a)
,然后创建fun5
和fun6
function c(){
c.super_.call(this)
console.log("constructor-c");
}
util.inherits(c,a);
c.prototype.fun5 = function(){
console.log("c-fun1");
}
c.prototype.fun6 = function(){
console.log("c-fun2");
}
这是因为
util.inherits的实现。该函数将把c
的原型重新分配给父对象的原型,而不是合并。因此,让util.inherits
首先将b
的原型分配给c
,然后添加所需的额外函数。util.inherits
需要在分配给原型之前调用。