Let's say I do the following code:
class Test
t: ->
"hell"
d: ->
console.log t()
"no"
It will pile to something like:
(function() {
this.Test = (function() {
function Test() {}
Test.prototype.t = function() {
return "hell";
};
Test.prototype.d = function() {
console.log(t());
return "no";
};
return Test;
})();
}).call(this);
Ok, I can't call the method t()
inside the d()
method.
Why not? How can I fix it?
Thanks in advance.
Let's say I do the following code:
class Test
t: ->
"hell"
d: ->
console.log t()
"no"
It will pile to something like:
(function() {
this.Test = (function() {
function Test() {}
Test.prototype.t = function() {
return "hell";
};
Test.prototype.d = function() {
console.log(t());
return "no";
};
return Test;
})();
}).call(this);
Ok, I can't call the method t()
inside the d()
method.
Why not? How can I fix it?
Thanks in advance.
Share Improve this question asked Jan 15, 2013 at 20:45 caarlos0caarlos0 20.7k27 gold badges89 silver badges160 bronze badges1 Answer
Reset to default 10class Test
t: ->
"hell"
d: ->
console.log @t()
# ^ Added
"no"
In CoffeeScript, as in Javascript, methods on the prototype must be accessed as properties of this
. CoffeeScript has shorthand for this
, the @
character. @t()
piles to this.t()
. And this.t()
will execute Test.prototype.t()
in the context on the instance you called it on.