Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" in a method call in TypeScript?

How do I want to make this work:

class TestClass {

   doMethod1 (arg1, arg2, cb)
   {
      this.doMethod2(arg1, arg2, function (result){cb (result)});
   }

  doMethod2 (arg1, arg2, cb) {
      this.doMethod3(arg1, arg2, function(result){cb (result)});
   }

  doMethod3 (arg1, arg2, cb) {
      var result = arg1 + arg2;
      cb(result);
   }
}

test = new TestClass;

test.doMethod3(1,1, cb); test.doMethod2(1,1,cb);

Both work.

test.doMethod1(1,1,cb);

EDIT: Actually, it does work.

I got around related lexical scoping issues by using the "fat arrow" syntax:

doMethod1 (arg1, arg2, cb)
   {
      this.doMethod2(arg1, arg2, (result) => {cb (result)});
   }

Ensures that the "this" in doMethod1 is the same as the "this" in the anonymous callback function.

like image 335
Josh Wulf Avatar asked Oct 26 '12 01:10

Josh Wulf


People also ask

How do you use this in TypeScript?

The "this" keyword always points to the object that is calling a particular method. The type of "this" in an expression depends on the location in which the reference occurs: In a constructor, member function, or member accessor, this is of the class instance type of the containing class.

What does () => void mean TypeScript?

According to the TypeScript docs: void represents the return value of functions which don't return a value. Whenever you see a function returning void , you are explicitly told there is no return value. All functions with no return value have an inferred return type of void .

What is the this keyword in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.

How do you call a function with parameters in TypeScript?

A Function is a block of code that you can use multiple times in an application. It can require one or more parameters. A list of parameters in parentheses, and a block of code in braces. To call a function, you code the function name followed by the function's parameters or arguments in parentheses.


1 Answers

To preserve the lexical scoping of this in TypeScript, you use Arrow Function Expressions.

They are defined in section 4.9.2 of the TypeScript Language Specification.

ArrowFormalParameters => { return AssignmentExpression ; }

Which in code can look like:

() => { alert(this.arg1); }
like image 176
Fenton Avatar answered Sep 22 '22 22:09

Fenton