Last active
November 29, 2017 01:40
-
-
Save w1shen/5123362 to your computer and use it in GitHub Desktop.
Parasitic Combination Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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