Skip to content

Instantly share code, notes, and snippets.

@coderek
Last active December 29, 2015 07:49
Show Gist options
  • Save coderek/7638597 to your computer and use it in GitHub Desktop.
Save coderek/7638597 to your computer and use it in GitHub Desktop.
demostrate mixins and open class
// mixin 1
var SuperAbility = {
dance: function () {
console.log (this.name + " is dancing...");
},
talk: function () {
console.log ("talking from mixin...");
}
}
// mixin 2
var SuperIntelligence = {
think: function () {
console.log (this.name + " is thinking...");
}
}
var Animal = function (name) {
this.name = name;
};
Animal.prototype.walk = function () {
console.log(this.name + " is walking...");
}
var duck = new Animal("duck");
var dog = new Animal("dog");
dog.walk(); // dog is walking...
// open class
Animal.prototype.talk = function () {
console.log(this.name + " is barking...");
};
// mixins
// also can extend Animal.prototype so mixins will apply to all animals
_.extend(dog, SuperAbility, SuperIntelligence);
_.extend(duck, SuperAbility, SuperIntelligence);
// shadowed method
dog.talk(); // talking from mixin
dog.think();
// calling parents method (only when mixin is applied to instance object)
dog.constructor.prototype.talk.apply(dog); // dog is barking..
dog.dance(); // dog is dancing...
duck.dance();
duck.think();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment