Created
January 19, 2015 14:19
-
-
Save hwclass/8f16e1b1e14230dbe214 to your computer and use it in GitHub Desktop.
JS Prototypal Inheritance Practical Example 1
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
// Declaring our Animal object | |
var Animal = function () { | |
this.name = 'unknown'; | |
this.getName = function () { | |
return this.name; | |
} | |
return this; | |
}; | |
// Declaring our Dog object | |
var Dog = function () { | |
// A private variable here | |
var private = 42; | |
// overriding the name | |
this.name = "Bello"; | |
// Implementing ".bark()" | |
this.bark = function () { | |
return 'MEOW'; | |
} | |
return this; | |
}; | |
// Dog extends animal | |
Dog.prototype = new Animal(); | |
// -- Done declaring -- | |
// Creating an instance of Dog. | |
var dog = new Dog(); |
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 Shape(x, y) { | |
this.x = x; | |
this.y = y; | |
} | |
// 1. Explicitly call base (Shape) constructor from subclass (Circle) constructor passing this as the explicit receiver | |
function Circle(x, y, r) { | |
Shape.call(this, x, y); | |
this.r = r; | |
} | |
// 2. Use Object.create to construct the subclass prototype object to avoid calling the base constructor | |
Circle.prototype = Object.create(Shape.prototype); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment