Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alias for 'this' in TypeScript?

I've attempted to write a class in TypeScript that has a method defined which acts as an event handler callback to a jQuery event.

class Editor {     textarea: JQuery;      constructor(public id: string) {         this.textarea = $(id);         this.textarea.focusin(onFocusIn);     }      onFocusIn(e: JQueryEventObject) {         var height = this.textarea.css('height'); // <-- This is not good.     } } 

Within the onFocusIn event handler, TypeScript sees 'this' as being the 'this' of the class. However, jQuery overrides the this reference and sets it to the DOM object associated with the event.

One alternative is to define a lambda within the constructor as the event handler, in which case TypeScript creates a sort of closure with a hidden _this alias.

class Editor {     textarea: JQuery;      constructor(public id: string) {         this.textarea = $(id);         this.textarea.focusin((e) => {             var height = this.textarea.css('height'); // <-- This is good.         });     } } 

My question is, is there another way to access the this reference within the method-based event handler using TypeScript, to overcome this jQuery behavior?

like image 298
Todd Avatar asked Oct 06 '12 03:10

Todd


People also ask

What are type aliases in TypeScript?

In Typescript, Type aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you'd have to define by hand otherwise. Aliasing doesn't truly create a new type; instead, it gives that type a new name.

What is this in TypeScript?

Introduction. One of the most important concepts to grasp in TypeScript is the use of the "this" keyword, which is used in object methods. The "this" keyword always points to the object that is calling a particular method.

What are type aliases in JavaScript?

A type alias is basically a name for any type. Type aliases can be used to represent not only primitives but also object types, union types, tuples and intersections.

What is type assertion in TypeScript?

In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn't reconstruct code. You can use type assertion to specify a value's type and tell the compiler not to deduce it.


1 Answers

The scope of this is preserved when using the arrow function syntax () => { ... } - here is an example taken from TypeScript For JavaScript Programmers.

var ScopeExample = {    text: "Text from outer function",    run: function() {      setTimeout( () => {        alert(this.text);      }, 1000);    }  }; 

Note that this.text gives you Text from outer function because the arrow function syntax preserves the "lexical scope".

like image 109
Fenton Avatar answered Sep 17 '22 02:09

Fenton