Guest User

Untitled

a guest
Nov 21st, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. # =======================================================================
  2. # INCORRECT
  3. # =======================================================================
  4.  
  5. class Foo
  6. # don't expect this to be an instance variable. it is not!! it is the
  7. # java equivalent of: public static colours = new Array()
  8. colours: []
  9.  
  10. addColour: (colour) =>
  11. # i believe java wouldn't even compile this with this.colours, but
  12. # Javascript is such a whore sometimes, it lets it pass without
  13. # complaining
  14. @colours.push colour
  15.  
  16. bar = new Foo()
  17. bar.addColour "red"
  18.  
  19. console.log bar.colours
  20.  
  21. # [ "red" ]
  22.  
  23. bat = new Foo()
  24. bat.addColour "orange"
  25.  
  26. console.log bat.colours
  27.  
  28. # [ "red", "orange" ]
  29.  
  30. # ^^^ ack!
  31.  
  32. # =======================================================================
  33. # CORRECT
  34. # =======================================================================
  35.  
  36. class Foo
  37. constructor: =>
  38. # initialize instance variables in your object's constructor
  39. @colours = []
  40.  
  41. addColour: (colour) =>
  42. @colours.push colour
  43.  
  44. bar = new Foo()
  45. bar.addColour "red"
  46.  
  47. console.log bar.colours
  48.  
  49. # [ "red" ]
  50.  
  51. bat = new Foo()
  52. bat.addColour "orange"
  53.  
  54. console.log bat.colours
  55.  
  56. # [ "orange" ]
Add Comment
Please, Sign In to add comment