简体   繁体   English

继承两个类-Javascript

[英]Inherit two classes - Javascript

I'm creating a new class definition Button that extends an existing Container class in EaselJS. 我正在创建一个新的类定义Button ,以扩展EaselJS中现有的Container类。 There are no problems with that. 没问题。 However, I'd also like Button to inherit from a super class All , so that Button also has access to its .banana and .eatBanana . 但是,我还希望Button可以从超类All继承,以便Button也可以访问其.banana.eatBanana How do I go about this? 我该怎么办?

(function() {

    function All() {
        this.banana = 0;
    }
    var p = All.prototype;

    p.eatBanana = function() {
        alert(this.banana);
    }

    window.All = All;
}());

(function() {

    function Button(apple) {
        this.apple = apple || 0;
        this.Container_constructor();
    }
    var p = createjs.extend(Button, createjs.Container);

    p.sayHi = function() {
       alert(this.apple + this.banana);
    }

    window.Button = createjs.promote(Button, 'Container');
}());

Javascript, and by extension CreateJS, does not support multiple inheritance. Javascript(通过扩展名CreateJS)不支持多重继承。 You could: 你可以:

  1. rethink your inheritance structure (ex. have Button extend All which extends Container) 重新考虑您的继承结构(例如,让Button扩展全部扩展容器)
  2. mix-in members from All into your Button class or instances: Button.prototype.doSomething = All.prototype.doSomething or myButton.doSomething = All.prototype.doSomething . 将All中的混合成员添加到Button类或实例中: Button.prototype.doSomething = All.prototype.doSomethingmyButton.doSomething = All.prototype.doSomething
  3. inject members into a super class such as DisplayObject that is extended by all of the classes you want the members on: DisplayObject.prototype.doSomething = All.prototype.doSomething . 将成员注入到诸如DisplayObject之类的超类中,该类由您希望成员在其上的所有类扩展: DisplayObject.prototype.doSomething = All.prototype.doSomething

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM