【问题标题】:Is multiple inheritance possible in javascript? [duplicate]javascript中可以多重继承吗? [复制]
【发布时间】:2023-03-06 21:20:02
【问题描述】:

我这里有个情况。我有两个这样定义的模块(除了 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; 
});

如何将两个模块都继承到其他模块中?

【问题讨论】:

标签: javascript


【解决方案1】:

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

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

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

【讨论】:

  • 那么...多重原型继承可能...?
  • 使用 mixins,这是最接近的。 Js 不强制执行结构或基类方法或属性..在 js 中,一切都只是一个对象..
【解决方案2】:

这里是你想要实现的功能的小演示:

var obj1 = function() {
  var privateMember = "anything";
  this.item1 = 1;
}

var obj2 = function() {
  this.item2 = 2;
}

var objInheritsBoth = function() {
  obj1.call(this); // call obj1 in this context
  obj2.call(this);
  this.item3 = 3;
}

var x = new objInheritsBoth();

console.log(x.item1, x.item2, x.item3); // 1 2 3

【讨论】:

    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2018-06-24
    • 1970-01-01
    相关资源
    最近更新 更多