javascript - javascript中是否可以进行多重继承?

标签 javascript

<分区>

我这里有个情况。我有两个模块(只有 javascript 函数)定义如下:

模块 1:

define(function(){
    function A() {
        var that = this;
        that.data = 1
        // ..
    }
    return A; 
});

模块 2:

define(function(){   
    function B() {
        var that = this;
        that.data = 1;
        // ...
    }
    return B; 
});

如何在其他模块中继承这两个模块?

最佳答案

1) 在 js 中,一切都只是一个对象。

2) Javascript 继承使用原型(prototype)继承而不是经典继承。

JavaScript 不支持多重继承。 要将它们都放在同一个类中,请尝试使用无论如何都更好的 mixin:

function extend(destination, source) {
  for (var k in source) {
    if (source.hasOwnProperty(k)) {
      destination[k] = source[k];
    }
 }
 return destination; 
 }

 var C = Object.create(null);
 extend(C.prototype,A);
 extend(C.prototype,B);

混入:

http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/

js中的继承:

http://howtonode.org/prototypical-inheritance

http://killdream.github.io/blog/2011/10/understanding-javascript-oop/index.html

关于javascript - javascript中是否可以进行多重继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16628250/

相关文章:

javascript - 字符串化一个对象然后将其解析回其原始对象?

javascript - 使用 openpgp 库在 Node 上运行时出现意外的标识符

javascript - Angular js错误: [$injector:modulerr] Failed to instantiate module ngroute due to:

javascript - IONIC 1 项目的 ionic 服务,不适用于 ionic 4 cli

javascript - 无法使用 jQuery 覆盖 jQuery 生成的内联样式?

javascript - 是否有在 JavaScript RegEx 匹配中检索组的特定方法?

javascript - 为什么 Javascript 动态 HTML5 表格没有出现在页面上

javascript - namespace 对象如何在 JavaScript 中与 AMD 一起使用?

javascript - 根据选择列表中所选的选项运行函数? (没有 jQuery 是首选)

JavaScript:单击按钮时无法更改 div 的背景颜色