javascript - 这个例子可以被认为是javascript中的多重继承吗?

标签 javascript inheritance

我听说 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 函数需要有一个指向 AB 实例的原型(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/

相关文章:

javascript - 如何从 json footable 获取数组

javascript - Web 应用程序中 Javascript 和 PHP 脚本之间的通信

c++ - 为什么模板函数不能将指向派生类的指针解析为指向基类的指针

java - 为什么Java不允许我通过同一个类的方法访问私有(private)方法?

c++ - 在 C++ 类继承中使用函数

Python:如何用最少的代码扩展一个巨大的类?

javascript - 使用 php 循环 WordPress 的响应式框布局

javascript - 单元测试中的去抖函数 'not a function'

javascript - Selenium WebDriver 等到元素显示

c++ - 错误 : ‘length’ was not declared in this scope c++