A recent project, the use of typescript to write JS script, the results are riddled with errors, repair also let me summarize the TS in how to use this.
TS provides static types similar to C # and Java (strongly typed), declaring a function directly in global and namespace global and using the Functions keyword (which is the function keyword of JS), while in class you cannot use function to declare a method. Let's compare it to the C # difference
public delegate int handle ();
public class program
{public
static void Main (string[] args)
{
var t = new Test ();
var a = new A ();
T.h = A.hander;
T.count = T.h ();
Console.WriteLine ("Count Is:{0}", T.count);
Output:
//Count Is:1
}
} public
class Test
{public
handle H;
public int count = +;
}
public class A
{
private int count = 0;
public int hander ()
{
this.count +=1;
return this.count;
}
}
This code put a method in Class A, and the method as a delegate to the class program's H field, and finally in the Main method to transport an H delegate, the result is 1 this result (a.count + 1 = 0 + 1 = 1)
Let's implement the same functionality in Typescript:
Class A {public
count:number = 0;
Public hander (): number {
This.count + = 1;
return this.count;
}
}
Class Test {public
count:number = +;
Public h: () = number;
}
Class Program {
static Main (): void {let
t = new Test ();
Let A = new A ();
T.h = A.hander;
T.count = T.h ();
Console.log (' Count is: ${t.count} ');
Output
//Count is:101
}
}
Program.main ();//In order to be consistent with C #, the provided static entry
You will find that the result is no longer 1, but 101, the reason for the difference is the this pointer js , in C # always point to the current class, and JS in this can change, when t.h = A.hander t.h thi s becomes the Test class. In Typescript, because a class is currently defined, its this always points to a class, so TS uses the this in JS directly.
But is there a way to solve this problem? Of course. Let's change class A.
Class A {
constructor () {
This.hander = () =>{
this.count + = 1;
return this.count;
}
}
Public count:number = 0;
Public hander: () = number;
}
In this way we turn hander from the method of the class into a variable of class, and More importantly we use the LAMDA expression in the constructor , using the LAMDA expression does not change the scope of this, because it is currently a constructor, so the inside of this point is The current class, (look at the generated JS will be easier to understand, the function has no this)
From the JS point of view, because the function does not have the this pointer, so it will not be passed to other places caused by inconsistent conditions