A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/microsoft/TypeScript/issues/15 below:

typechecking of 'this' context · Issue #15 · microsoft/TypeScript · GitHub

A common error in TypeScript is to lose the this context, especially in class situations:

class MyClass {
    x = 4;
    printX() { console.log(this.x); }
}
var m = new MyClass();
window.setInterval(m.printX, 1000); // Prints 'undefined', not '4'

The compiler should detect when this happens and issue an error:

var m = new MyClass();
// Error, `this` context might be lost
window.setInterval(m.printX, 1000);

We need a proposal here that determines why this would be an error, in a way that is not burdensome. For example, we do want it to be valid to call e.g. function#bind on m.printX, and it should probably valid to write something like if(m.printX) { m.printX() }.

This gets even trickier when we look at the members of window -- some of them can be invoked with any this, but others cannot. It should be possible to describe these differences.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4