Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Created March 3, 2012 20:58
Show Gist options
  • Save FireyFly/1968192 to your computer and use it in GitHub Desktop.
Save FireyFly/1968192 to your computer and use it in GitHub Desktop.
// Foo is a simple type with a unique ID for each instance.
var idCounter = 0
function Foo() {
this.id = (++idCounter) // assign a unique ID to this instance
}
Foo.prototype.getID = function() {return this.id}
// We make sure that it's working as intended by creating two instances.
var foo = new Foo()
, foo2 = new Foo()
console.log(foo.getID()) // 1
console.log(foo2.getID()) // 2
// `foo.id` is `1`, `foo2.id` is `2`. Looks good.
// Now we want our new type Bar to inherit from Foo.
function Bar() { }
Bar.prototype = new Foo()
// since we're creating a *new instance of Foo* here, this means that
// `Bar.prototype.id` will be `3`. Since `Bar.prototype.id` is 3, this
// value will be propagated to all instances of `Bar`. Probably not
// what we wanted!
var bar = new Bar()
, bar2 = new Bar()
console.log(bar.getID()) // 3
console.log(bar2.getID()) // 3
// Uh-oh. Both `bar.id` and `bar2.id` will be `2`, since that's the
// value of the property 'id' in `Bar.prototype`. The "private" id that
// the `Foo` constructor sets is visible to all instances of `Bar`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment