Typescript object literal "this" keyword
You’re using an arrow function, which has lexical this
.
The shorthand for a non-arrow function property in an object literal is even shorter, though:
var fooObj: foo = {
bar() {
console.log(this.baz);
}
}
Setting the "noImplicitThis": true
compiler option is how you would enable this functionality now. This pull request enabled typed this
in object literals. Aleksey L originally suggested this compiler option in a comment on the question, but at the time it didn't function that way.
This answer was true at the time of the question. This have since changed with new versions of typescript and target javascript versions.
You are asking typescript to infer that this
is fooObj
.
Typescript binds this
by creating a local variable _this
, that is bound to the this
-context where the fat-arrow is declared. And in your case, this
is the global scope, which is any
. This is what it gets compiled into:
var _this = this;
var fooObj = {
bar: function () {
// TS does not error out when I access this.baz
console.log(_this.baz);
}
};
This is how it looks like within a class:
class Bar
{
private var = 23;
public makeSound = () => console.log(this.var)
}
// Compiles into:
var Bar = (function () {
function Bar() {
var _this = this;
this.var = 23;
this.makeSound = function () { return console.log(_this.var); };
}
return Bar;
}());