Skip to content

Instantly share code, notes, and snippets.

@aarti
Last active August 29, 2015 14:10
Show Gist options
  • Save aarti/c507aa5aa5bcfd6807f3 to your computer and use it in GitHub Desktop.
Save aarti/c507aa5aa5bcfd6807f3 to your computer and use it in GitHub Desktop.
Javascript prototype inheritance
// There are several ways to instantiate objects in Javascript and show how the prototype chaining works.
// I have demonstrated two such ways here
// Prototype inheritance Using Object.create()
house = { rooms: 4, square_foot: 2000 };
// Creates an object house, whose prototype is Object.prototype
house_in_sf = Object.create(house);
// Creates an object house_in_sf, whose prototype is house, and goes up the chain to Object.prototype and then to null
house_in_sf.square_foot = 800
console.log(house_in_sf.rooms) // returns 4
console.log(house_in_sf.square_foot) // returns 800
console.log(house_in_sf.__proto__) // returns { rooms: 4, square_foot: 2000 }
console.log( house.__proto__) // returns literal {}
// constructor + prototype
// In this example we see how prototype is used for inheriting behavior from other objects.
var Media = function() {
this.hasText = true;
this.describe = function() {
if (this.hasText) {
console.log('Media-text' + this.description);
}
else {
console.log('No text provided for media');
}
};
};
var Book = function(title, description) {
this.title = title;
this.description = description;
this.describe = function() {
if (this.hasText) {
console.log("Title:" + this.title + ",Description:" + this.description);
}
};
};
Book.prototype = new Media();
var VoiceMemo = function(description) {
this.description = description;
this.hasText = false;
};
VoiceMemo.prototype = new Media();
var book1 = new Book("Wonder", "A children's novel about a 5th grade boy");
book1.describe()
// Returns Title: Wonder, Description: A children's novel about a 5th grade boy
var voiceMemo = new VoiceMemo("Call From JK Rowling")
voiceMemo.describe()
// Returns 'No text provided for media'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment