Skip to content

Instantly share code, notes, and snippets.

@joshbeckman
Created October 12, 2015 14:19
Show Gist options
  • Save joshbeckman/b07bc373931a96eb55d3 to your computer and use it in GitHub Desktop.
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
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."
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."
@joshbeckman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment