-
Notifications
You must be signed in to change notification settings - Fork 889
Feature: Disallow 'this' in non-arrow closure functions #219
Comments
There are legal use cases like this one: var obj = {threshold: 10};
var filtered = [12, 5, 8, 130, 44].filter(function isBigEnough(element) {
return element >= this.threshold;
}, obj); And one of the reasons to use typescript is taking advantage of arrow functions: $( "#target" ).click(() => {
this.onClick();
}); |
@awerlang Yes, there are use cases like the one you are pointing out where using I am not sure whether I am getting your point with your 2nd example. The arrow function does not change the semantics of var self = myObjectWithOnClick;
$( "#target" ).click(() => {
self.onClick();
}) |
Actually the arrow function notation takes export class Controller {
constructor(el) {
$( el ).click(() => {
this.onClick();
});
}
onClick() {
alert("clicked!");
}
}
var ctrl = new Controller("#target"); |
@awerlang You are right, I stand corrected! I just went to http://www.typescriptlang.org/Playground/ and compiled your example. define(["require", "exports"], function (require, exports) {
var Controller = (function () {
function Controller(el) {
var _this = this;
$(el).click(function () {
_this.onClick();
});
}
Controller.prototype.onClick = function () {
alert("clicked!");
};
return Controller;
})();
exports.Controller = Controller;
var ctrl = new Controller("#target");
}); The compiler clearly picked up Circling back to my original feature request... What I am hearing you say between the lines is: "If you are concerned about incorrect usage of I would agree to that, but then the next thing I would do is close this issue and open a new one with the title:
or even more radical:
The case I want myself protected against is using |
I would agree to "Feature: Disallow 'this' in non-arrow closure functions". If one were to disallow non-arrow functions, then it would become impossible to declare anonymous constructor functions, because |
ok, I am changing the title from
to
Thanks for your input! |
I believe TypeScript 2 with With See example: class User {
constructor(public name: string) {
}
onReady(callback: () => void) {
callback.apply(this);
}
}
let user = new User("John");
user.onReady(function () {
console.log(this.name);
}); TypeScript will report an error on usage of But if you specify onReady(callback: (this: User) => void) { It will not error out and work correctly. @bparadie so with |
Closing this feature request. With the added support of contextual |
A mistake, that is easy to make, is the accidental use of
this
in functions and anonymous functions, i.e.A common pattern to avoid that problem is using a proxy for
this
instead ofthis
in functions and anonymous functions, i.e.:Using
this
in member function of classes (methods) are of course allowed.Please consider adding a rule for disallowing 'this' in functions for
tslint
.The text was updated successfully, but these errors were encountered: