this in TypeScript

and JavaScript





@basarat

Default Context


It depends on the calling context. In the browser it is `window`
window.foo = 123;
function bar(){
    console.log(this.foo);
}bar();

Using `new`

If you call a function with the `new` operator it becomes the locally created object

Prefix

If you prefix it with something when calling it becomes the object calling it (i.e. the calling context)

APPLY

If you don't want to copy the function use `apply` (with [arguments]) or `call` (with arg1, arg2) available on the prototype of Function (so any function can be used or Function.prototype.)

Force the calling context 

You can force the calling context using `bind`

Lexical Scope

Using TypeScript. You can get around to the problem using `()=>` which retains the scope from outside.

Title

this in TypeScript

By basarat

this in TypeScript

  • 1,556