Skip to content

Instantly share code, notes, and snippets.

@geraldalewis
Created February 18, 2012 02:08
Show Gist options
  • Save geraldalewis/1856904 to your computer and use it in GitHub Desktop.
Save geraldalewis/1856904 to your computer and use it in GitHub Desktop.
Implicit `this` in CoffeeScript
class Sprite
@id: 0
id: -1
x: 0
y: 0
width: 0
height: 0
constructor: ->
id = ++Sprite.id # ~> this.id = ++Sprite.id
move: (x,y) ->
this.x = x
this.y = y
# `this` is sometimes still useful/necessary (identical params/class body vars)
getRect: ->
new Rectangle x, y, width, height
# ~> new Rectangle this.x, this.y, this.width, this.height
@jashkenas
Copy link

Agree with much of what @geraldalewis is saying above, but there's a much bigger problem than "lack of var". Ruby also doesn't have "var", and does have "implicit this", and it works beautifully.

But the reason why we can't do it is that our classes are dynamic. We have no idea, at compile time, what properties are on the prototype. You may have listed some in the class body, but more might be mixed in, more might be added to the prototype directly later in an extension file, and you might yourself be subclassing from an external script that we're not compiling. If we had access to the runtime method resolution, we'd be able to know, but at compile type JS is too dynamic to find out.

Unlike our current pure lexical scope for implicit 'var'....

@geraldalewis
Copy link
Author

Ruby also doesn't have "var", and does have "implicit this", and it works beautifully.

Interesting... Time for me to finally finish the pickaxe book :)

and you might yourself be subclassing from an external script that we're not compiling.

Great point. I'm accustomed to compilers that require all the source up front. That actually ties into #558 (debug support). One of the big challenges is what to do when CoffeeScript code calls buggy code from a precompiled CoffeeScript file. Since the compiler doesn't have access to the original CoffeeScript, the compiler can't show the original line of code responsible for the error (without an intermediary form like a source map).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment