Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Created March 19, 2012 11:58
Show Gist options
  • Save FireyFly/2109224 to your computer and use it in GitHub Desktop.
Save FireyFly/2109224 to your computer and use it in GitHub Desktop.
Constructor functions vs. "pure prototypal inheritance"
// 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")
*/
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