Created
March 19, 2012 11:58
-
-
Save FireyFly/2109224 to your computer and use it in GitHub Desktop.
Constructor functions vs. "pure prototypal inheritance"
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
// Assume `Object.prototype.extend` exists. | |
var Foo = { | |
/* stuff that would go in Foo.prototype */ | |
} | |
var Bar = Foo.extend({ | |
/* stuff that would go in Bar.prototype */ | |
}) | |
var bar = Bar.extend({ foo:10, bar:[1,2,3] }) | |
// if we need to *initialise* the object after it has been created, we can simply | |
// create a function that does that explicitly, and then do | |
var Baz = { | |
init: function(...) { | |
... | |
return this | |
} | |
} | |
var baz = Baz.extend({}).init(1, 2, 3) // or whatever | |
// usually this is not the case, however (for me at least). | |
/* | |
Foo | |
/\ | |
|| | |
|| | |
Bar | |
/\ | |
|| | |
|| | |
bar | |
a ===> b "a inherits from b" (or "a's [[Prototype]] is b") | |
*/ |
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 Foo() { | |
... | |
} | |
function Bar() { | |
Foo.call(this) | |
... | |
} | |
Bar.prototype = Object.create(Foo) // or `new Foo`, or whatever | |
var bar = new Bar() | |
/* | |
Foo --- Foo.prototype | |
^ /\ | |
| || | |
| || | |
Bar --- Bar.prototype | |
/\ | |
|| | |
|| | |
bar | |
a ---> b "a calls b" | |
a ===> b "a inherits from b" (or "a's [[Prototype]] is b") | |
a ---- b "a and b are related" (have references to each other) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment