Skip to content

Instantly share code, notes, and snippets.

@pgib
Created July 4, 2012 19:50
Show Gist options
  • Select an option

  • Save pgib/3049232 to your computer and use it in GitHub Desktop.

Select an option

Save pgib/3049232 to your computer and use it in GitHub Desktop.
An easy thing to overlook with classes and instance variables in Javascript
# =======================================================================
# INCORRECT
# =======================================================================
class Foo
# don't expect this to be an instance variable. it is not!! it is the
# java equivalent of: public static colours = new Array()
colours: []
addColour: (colour) =>
# i believe java wouldn't even compile this with this.colours, but
# Javascript is such a whore sometimes, it lets it pass without
# complaining
@colours.push colour
bar = new Foo()
bar.addColour "red"
console.log bar.colours
# [ "red" ]
bat = new Foo()
bat.addColour "orange"
console.log bat.colours
# [ "red", "orange" ]
# ^^^ ack!
# =======================================================================
# CORRECT
# =======================================================================
class Foo
constructor: =>
# initialize instance variables in your object's constructor
@colours = []
addColour: (colour) =>
@colours.push colour
bar = new Foo()
bar.addColour "red"
console.log bar.colours
# [ "red" ]
bat = new Foo()
bat.addColour "orange"
console.log bat.colours
# [ "orange" ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment