Mixin's in Javascript

In Ruby, I could define a module and then include that in other classes so that those methods will be added to the class definition.


This way, I don't need to duplicate method definitions across different, unrelated classes.


How can I do this in Javascript?
JavaScript is very dynamic, you can easily assign new property for Object by something as easy like this: obj.aMethod = function() {}


Also, you can do this: obj1.newMethod = obj2.method, which will assign obj2's method to obj1 as name newMethod.


The easiest way to do this is creating a function to iterate all properties in Object B and assign them to Object A.


Further reading: https://addyosmani.com/resources/essentialjsdesignpatterns/book/#mixinpatternjavascript
I suggest you to take a look at PIXI.EventTarget, which implements a common way to do mixins in JavaScript.
Object.assign will be the standard way to merge two objects. You can polyfill it if you need to support IE as a browser.


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign


With Object.assign, you can mixin an object into an object's prototype, which will provide the mixin functionality:

Code:
function MyClass() {};

MyClass.prototype = ... //single inheritance

var mixin = {
  foo: bar
  fooMethod: function () { return this.foo; }
}

Object.assign(MyClass.prototype, mixin); //Mixin inheritance
It's ES6, though, and as such won't work in MV. You can still use the polyfill, though i would reword it, because adding to Object.prototype is never a good idea.

Original thread: https://forums.rpgmakerweb.com/threads/mixins-in-javascript.56699/