Reputation: 2535
Here is my coffeescript code.
class Hello
constructor: ->
@greetings()
this.greetings()
greetings()
greetings: ->
alert 'hello world'
new Hello
This code translates into
var Hello;
Hello = (function() {
function Hello() {
this.greetings();
this.greetings();
greetings();
}
Hello.prototype.greetings = function() {
return alert('hello world');
};
return Hello;
})();
new Hello;
In the third case in the coffeescript code I neither used @
nor this
. I was assuming that coffeescript would use implicit this but that does not seem to the case.
I did a quick google search but did not get any result. So can anyone confirm that coffeescript does not support implicit this.
Upvotes: 1
Views: 855
Reputation: 187024
Coffeescript does not support implicit this
. Mostly because coffee script is really just sugar for javascript, and in javascript this would be a very bad idea, given that functions are first class objects and can be assigned to local variables.
How would access local variables then?
a = -> 123
@a = -> 456
// normal coffeescript
a() # 123
// with implicit this
a() # 123 or 456? Impossible to know.
It important to remember that in java script var a;
and this.a
have no relation to each other and are always 2 separate variables. Knowing when you are addressing which is really important.
Lastly, this is why the @
notation was created. When using a class based style in javascript it becomes very common to reference properties of this
with this.propName
all over the place. @
was added to coffee script be less tedious and annoying when programming in this fashion.
Upvotes: 4