Skip to content

Instantly share code, notes, and snippets.

@Wizek
Created June 5, 2011 12:20
Show Gist options
  • Save Wizek/1008916 to your computer and use it in GitHub Desktop.
Save Wizek/1008916 to your computer and use it in GitHub Desktop.
Inheritance in JS
/*\
* Sometimes I'm amused by how versatile and expressive JavaScript
* can be when it comes to even the smallest of details at its core;
* like declaring inheritance patterns.
* [Or global variable declaration.](http://goo.gl/iqk1J)
*
* We are here to talk about the former, because other times it's a
* baffling experience to choose the right way.
*
* I've listed 5 ways of performing roughly the same task below.
* In the comments, tell me why/when you would or wouldn't use a
* particular one, and which one is your syntax of choice, and of
* course, why.
*
* Also, if you know about a method different from my listings, let
* me know and I'll add it!
*
* tl;dr
* Inheritance in JS. How? Why that way?
\*/
// This is how each is used:
var foo = new Foo()
foo.bar() // returns 'OK' if proper
// #1
var Foo = function() {
this.bar = function() {
return 'OK'
}
}
// #2
var Foo = function() {
var out = function() {}
out.bar = function() {
return 'OK'
}
return out
}
// #3
var Foo = function() {
var out = {}
out.bar = function() {
return 'OK'
}
return out
}
// #4
var Foo = (function() {
var Foo = function() {}
Foo.prototype.bar = function() {
return 'OK'
}
})()
// #5
var Foo = function() {}
Foo.prototype = (function() {
return {bar: bar}
function bar () {
return 'OK'
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment