Created
October 12, 2015 14:19
-
-
Save joshbeckman/b07bc373931a96eb55d3 to your computer and use it in GitHub Desktop.
An example showing the difference between prototypal inheritance and raw object usage in JavaScript
This file contains hidden or 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 Foo(who) { | |
this.me = who; | |
} | |
Foo.prototype.identify = function() { | |
return "I am " + this.me; | |
}; | |
function Bar(who) { | |
Foo.call(this,who); | |
} | |
Bar.prototype = Object.create(Foo.prototype); | |
// NOTE: .constructor is borked here, need to fix | |
Bar.prototype.speak = function() { | |
alert("Hello, " + this.identify() + "."); | |
}; | |
var b1 = new Bar("b1"); | |
var b2 = new Bar("b2"); | |
b1.speak(); // alerts: "Hello, I am b1." | |
b2.speak(); // alerts: "Hello, I am b2." |
This file contains hidden or 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
var Foo = { | |
init: function(who) { | |
this.me = who; | |
}, | |
identify: function() { | |
return "I am " + this.me; | |
} | |
}; | |
var Bar = Object.create(Foo); | |
Bar.speak = function() { | |
alert("Hello, " + this.identify() + "."); | |
}; | |
var b1 = Object.create(Bar); | |
b1.init("b1"); | |
var b2 = Object.create(Bar); | |
b2.init("b2"); | |
b1.speak(); // alerts: "Hello, I am b1." | |
b2.speak(); // alerts: "Hello, I am b2." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Object.create()
polyfill: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill