我听说 JavaScript 不支持多重继承。
下面的示例是否可以被视为多重继承,如果不是,那么有人可以解释一下为什么......吗?
function A () {
this.a = 'a'
};
function B () {
this.b = 'b'
};
function AB () {
A.call(this);
B.call(this);
};
var obj = new AB();
console.dir(obj);
//Output: {a: "a", b: "b"}
最佳答案
Can the below example be considered Multiple Inheritance?
没有
Can anyone please explain why?
您的 AB
(从这里开始我将其称为 C
)函数实际上并不扩展 A
也不会扩展 B
:
function A () {
this.a = 'a';
}
function B () {
this.b = 'b';
}
function C () {
A.call(this);
B.call(this);
}
a = new A();
console.log('a is A', a instanceof A);
b = new B();
console.log('b is B', b instanceof B);
c = new C();
console.log('c is A', c instanceof A, 'c is B', c instanceof B);
在该示例中,您根本没有任何继承权。你确实有函数组合。
如果您想要继承,C
函数需要有一个指向 A
或 B
实例的原型(prototype):
function A () {
this.a = 'a';
}
function B () {
this.b = 'b';
}
function C () {
A.call(this);
B.call(this);
}
C.prototype = new A();
//or
//C.prototype = new B();
a = new A();
console.log('a is A', a instanceof A);
b = new B();
console.log('b is B', b instanceof B);
c = new C();
console.log('c is A', c instanceof A, 'c is B', c instanceof B);
请注意,由于 C
函数具有单个原型(prototype),因此您只能具有单个继承。
对于对象组合,通常会看到以下模式:
function A () {
this.a = 'a';
}
function B () {
this.b = 'b';
}
function C () {
this.a = new A();
this.b = new B();
}
a = new A();
console.log('a is A', a instanceof A);
b = new B();
console.log('b is B', b instanceof B);
c = new C();
console.log('c.a is A', c.a instanceof A, 'c.b is B', c.b instanceof B);
关于javascript - 这个例子可以被认为是javascript中的多重继承吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38486059/