Created
July 4, 2012 19:50
-
-
Save pgib/3049232 to your computer and use it in GitHub Desktop.
An easy thing to overlook with classes and instance variables in Javascript
This file contains hidden or 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
| # ======================================================================= | |
| # 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