Skip to content

Instantly share code, notes, and snippets.

@lance
Last active February 10, 2016 14:32
Show Gist options
  • Save lance/fe447572015a3ccfba84 to your computer and use it in GitHub Desktop.
Save lance/fe447572015a3ccfba84 to your computer and use it in GitHub Desktop.
function mixin(obj, mix) {
for (var n in mix) {
// only mixin behavior, not data
var f = mix[n];
if (typeof f === 'function') {
obj[n] = f;
}
}
}
function Person (name, age) {
if (!(this instanceof Person)) {
return new Person(name, age);
}
this.name = name;
this.age = age;
}
var thingThatCanFly = {};
thingThatCanFly.fly = function () {
var flyingMessage = "";
if (typeof this.name !== "undefined") {
flyingMessage += "My name is " + this.name + " and ";
}
flyingMessage += "I'm flying!";
return flyingMessage;
};
var wingedPerson = new Person("Jennifer", 18);
mixin(wingedPerson, thingThatCanFly);
console.log(wingedPerson.fly());
console.log(wingedPerson.age);
//=> My name is Jennifer and I'm flying!
console.log("wingedPerson.hasOwnProperty('fly') " + wingedPerson.hasOwnProperty('fly'));
//=> true
var unnamedThing = {};
mixin(unnamedThing, thingThatCanFly);
console.log(unnamedThing.fly());
//=> I'm flying!
console.log("unnamedThing.hasOwnProperty('fly') " + unnamedThing.hasOwnProperty('fly'));
//=> true
// Now make Person.prototype capable of flight, which makes all newly
// created instances of Person capable of flight, but no longer do they
// haveOwnProperty('fly') because it's now inherited from the prototype.
mixin(Person.prototype, thingThatCanFly);
console.log("Person.prototype.hasOwnProperty('fly') " + Person.prototype.hasOwnProperty('fly'));
// new agnostic!
var sally = Person('Sally');
console.log(sally.fly());
//=> My name is Sally and I'm flying!
console.log("sally.hasOwnProperty('fly') " + sally.hasOwnProperty('fly'));
//=> false
// Note, however, that the original wingedPerson still hasOwnProperty('fly')
console.log("wingedPerson.hasOwnProperty('fly') " + wingedPerson.hasOwnProperty('fly'));
//=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment