Skip to content

Instantly share code, notes, and snippets.

@w1shen
Last active November 29, 2017 01:40
Show Gist options
  • Save w1shen/5123362 to your computer and use it in GitHub Desktop.
Save w1shen/5123362 to your computer and use it in GitHub Desktop.
Parasitic Combination Inheritance
function obj(o) {
function F() {}
F.prototype = o;
return new F();
}
function inheritPrototype(sub, sup) {
var p = obj(sup.prototype);
p.constructor = sub;
sub.prototype = p;
}
function Animal(name) {
this.name = name;
this.children = [];
}
Animal.prototype.alertName = function() {
alert(this.name);
};
Animal.prototype.alertChildren = function() {
alert(this.children);
};
function Dog(name, master) {
Animal.call(this, name); // inherit properties
this.master = master;
}
inheritPrototype(Dog, Animal); // inherit prototype
Dog.prototype.alertMaster = function() {
alert(this.master);
};
var d1 = new Dog("white", "walter");
var d2 = new Dog("black", "bob");
d1.children.push("w1");
d2.children.push(["b1", "b2"]);
d1.alertName();
d1.alertChildren();
d2.alertMaster();
d2.alertChildren();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment