Reputation: 6872
I wrote such object literal in TypeScript:
var object = {
message: "Say",
say: () => {
return this.message;
}
};
And I got such generated JavaScript:
var object = {
message: "Say",
say: function () {
return _this.message;
}
};
Shouldn't there be such line before return statement:
var _that = this;
as I am using arrow function expression?
Upvotes: 2
Views: 958
Reputation: 221212
=>
is a bit of a danger here because, critically, it binds this
to the enclosing scope's this
. In the correct code generation, the var _this = this;
line goes above the object literal and your say
function simply returns undefined
.
You only ever want to use this
in a =>
expression when you actually want to refer to this
that would be present in the enclosing scope. In this particular case, you don't (you want the interior scope this
, i.e. the object literal itself).
Upvotes: 2
Reputation: 953
You're correct. It's missing the :
var _this = this;
This is discovered after the release(0.8) and is currently fixed on the developer branch.
Note: Also I think you wanted to write
var object = {
message: "Say",
say: function () {
return () => this.message;
}
};
which will actualy print Say when it's run. See: http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax
Upvotes: 2