Last active
September 7, 2016 16:24
-
-
Save getify/5358821 to your computer and use it in GitHub Desktop.
A comparison of prototype-style of coding objects and Object.create()-style of coding objects. Both code snippets create two objects `b1` and `b2` which are `prototype` linked to behaviors defined by `Foo` and `Bar`. Take a look at both code snippets to see the pros and cons of each style of code, and decide for yourself which one is simpler to …
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); | |
//Bar.prototype.constructor = Bar; // uncomment this line to "fix" the delegated `constructor` | |
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." | |
// some reflection | |
b1 instanceof Bar; // true | |
b2 instanceof Bar; // true | |
b1 instanceof Foo; // true | |
b2 instanceof Foo; // true | |
Bar.prototype instanceof Foo; // true | |
Object.getPrototypeOf(b1) === Bar.prototype; // true | |
Object.getPrototypeOf(b2) === Bar.prototype; // true | |
Object.getPrototypeOf(Bar.prototype) === Foo.prototype; // true |
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." | |
// some reflection | |
Bar.isPrototypeOf(b1); // true | |
Bar.isPrototypeOf(b2); // true | |
Foo.isPrototypeOf(b1); // true | |
Foo.isPrototypeOf(b2); // true | |
Foo.isPrototypeOf(Bar); // true | |
Object.getPrototypeOf(b1) === Bar; // true | |
Object.getPrototypeOf(b2) === Bar; // true | |
Object.getPrototypeOf(Bar) === Foo; // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment