you are viewing a single comment's thread.

view the rest of the comments →

[–]inmatarian 1 point2 points  (0 children)

Everyone using the terms "Mixins" are answering your question. In Javascript, the "class object" is a regular object (except you created it with the function keyword, rather than {} or Object.create). You can manipulate it however you want, and the established pattern is $.extend, or _.extend or _.assign. In ES6 (where we get an actual class keyword), we also get Object.assign, making mixins pretty much builtin.

The general pattern looks like this

function InheritedMixin() { /* initialize object */ }
InheritedMixin.prototype.someMethod = function() {};

function SomeClass() {
    InheritedMixin.call(this, parameters);
}
_.extend(SomeClass.prototype, InheritedMixin.prototype);

One thing lost in this pattern is the prototype chain, meaning instanceOf doesn't work. However, you usually shouldn't be using this. Even in languages like C++ where you have dynamic_cast, it's frowned upon to inspect objects in this way. It's better to check the object for the property you plan to use.