相关疑难解决方法(0)

JavaScript中的组合,继承和聚合

关于组合与继承在线有很多信息,但我还没有找到适合JavaScript的例子.使用以下代码演示继承:

function Stock( /* object with stock names and prices */ ) {
    for (var company_name in arguments[0]) {
        // copy the passed object into the new object created by the constructor
        this[company_name] = arguments[0][company_name]; 
    }
}

// example methods in prototype, their implementation is probably redundant for
// this question, but list() returns an array with toString() invoked; total()
// adds up the stock prices and returns them. Using ES5 feature to make
// inherited properties non-enumerable 

Stock.prototype = …
Run Code Online (Sandbox Code Playgroud)

javascript oop inheritance composition

57
推荐指数
1
解决办法
2万
查看次数

用于ES6课程的Mixins,用babel编译

根据各种来源(2ality,esdiscuss),应该能够将mixins添加到类中:

编辑发现类方法不可枚举,因此无法工作.编辑了下面的代码,但仍然没有快乐

class CartoonCharacter {
  constructor(author) {
    this.author = author;
  }

  drawnBy() {
    console.log("drawn by", this.author);
  }
}

// THIS CANNOT WORK
// class methods are not enumerable
// class Human {
//  haveFun() {
//    console.log("drinking beer");
//  }
// }

let Human = Object.create({}, {
  haveFun:   {
    enumerable: true,
    value: function () {
      console.log("drinking beer");
    }
  }
});

class Simpson extends Object.assign(CartoonCharacter, Human) {
  constructor(author) {
    super(author);
  }
}


let homer = new …
Run Code Online (Sandbox Code Playgroud)

javascript traits composition mixins ecmascript-6

10
推荐指数
2
解决办法
6405
查看次数

好的做法:如何确保JavaScript构造函数可以访问mixin函数?

作为RPG游戏后端的一部分,我希望能够对角色应用临时效果.这些效果的性质可能会有很大差异,但我想保持定义它们的方法非常简单.

我正在使用自定义事件处理作为mixin:

var EvtObject = {};
$rpg.Event.enable(EvtObject); // Add the 3 methods and set EvtObject._events = {}
Run Code Online (Sandbox Code Playgroud)

我想将Auras(临时效果)定义为具有事件处理代码的构造函数:

var MyAura = function(any, args){
  this.group = "classification";
  this.on( "tick", function(){} );
  this.on( "remove", function(){} );
};
Run Code Online (Sandbox Code Playgroud)

然后应用为MyCharacter.addAura(new MyAura(any, args));.如您所见,我希望该this.on()函数在构造函数中可用.如果我使用mixin($rpg.Event.enable(MyAura.prototype))扩展MyAura原型,那么MyAura的每个实例都会引用_events原型中的相同对象.

我想知道以下解决方案是否是良好的做法:

Aura.create = function(Constructor)
{
    Constructor.prototype = Aura.getPrototype(); // Aura specific prototype

    return function()
    {
        var newAura = Object.create(Constructor.prototype);
        $rpg.Event.enable( newAura );
        Constructor.apply( newAura, arguments );
        return newAura;
    };

};

// Then creating new …
Run Code Online (Sandbox Code Playgroud)

javascript closures delegation composition mixins

6
推荐指数
1
解决办法
285
查看次数

如何在Javascript中正确使用mixins

我正在组织一个小型企业应用程序,但希望尽可能干.结果,我一直在关注mixin库.

我遇到了这个并认为这可能是一个不错的选择,因为它允许你在运行时混合进出.此外,我可以只有一个基类(BaseView),只是混合它.

问题

  1. 什么是有用的Mixins的实际应用示例?(请不要再抽象例子)
  2. 我是否甚至需要扩展类,或者我可以使用此库来管理所有扩展和mixins?

javascript dry mixins

5
推荐指数
1
解决办法
2551
查看次数