I’m very new in coffeescript and also with objects in javascript.
I have this piece of code in coffeescript:
class Animal
constructor: (name) ->
@name = name
@upperName: ->
@name.toUpperCase()
@greetings ->
console.log 'Hello %s', @name
this.type = 'Animal'
That is “compiled” into this javascript:
var Animal
Animal = (function() {
function Animal(name) {
this.name = name;
({
this.upperName: function() {
return this.name.toUpperCase();
}
});
this.greetings(function() {
return console.log('Hello %s', this.name);
});
}
Animal.type = 'Animal';
return Animal;
})();
What’s the difference between the methods greetings and upperName???
What the “:” do in a class?
Thanks
Symbol summary (left=CS, right=JS)
Within
class Animal:Elsewhere (ordered by same compiled result)
In CoffeeScript, @ compiles to
this.In the context of a
classconstruct, the method definition is affected by use of@(this). Here’s a simple example:Although the syntax slightly differs, the latest two have the same compiled result.
"What does
:mean inside a class block?"It is used to define properties. When
=(is equal sign) is used instead, a "private" variable will be defined."What does
:mean inside the (constructor) method?Outside the level of a class (eg top-level code, inside a function, constructor, etc.),
:does not have the "special class" meaning.:is the separator between key-name pairs within an object literal.Your given code,
@upperName: -> ...is invalid, and does not compile in the latest CoffeeScript version.upperName: -> ...is valid though, and will compile to an object literal with propertyupperNameand a function as a value.Have a look at the compiled CoffeeScript code: