This is the 28th day of my participation in the August Challenge

In JavaScript, this has always been a popular question for job interviewers, especially regarding the orientation of this, so today we’ll talk about the orientation of this in TypeScript classes and methods.

It’s important to remember that TypeScript doesn’t change the runtime behavior of JavaScript, which has some unique runtime behavior.

class MyClass {
    name = "MyClass";
    getName() {
      return this.name; }}const c = new MyClass();
  const obj = {
    name: "obj".getName: c.getName,
  };
   
  // Prints "obj", not "MyClass"
  console.log(obj.getName());
Copy the code

To make a long story short, by default, what this represents in a function depends on how the function is called. In this case, because the function is called by an obj reference, the this value is obj and not the class instance. That’s rarely what you want to happen! TypeScript provides ways to mitigate or prevent such errors.

Arrow function

How often do you lose the context object ·this when calling a function? You can solve this problem by using arrow functions instead of normal functions.

The Call, apply, and bind methods are not suitable for arrow functions because they are designed to allow methods to be executed in different scopes. Because the arrow function defines this according to the scope defined by the arrow function.

class MyClass {
    name = "MyClass";
    getName = () = > {
        return this.name; }}const c = new MyClass();
const obj = {
    name: "obj".getName: c.getName,
};

// Prints "obj", not "MyClass"
console.log(obj.getName());
Copy the code

There are trade-offs

  • Even in the absence ofTpyeScriptIn the case of code inspections, guarantees are also required at run timethisValue is guaranteed to be used correctly
  • This takes up more memory because each instance of the class will have a copy of the methods defined this way
  • Cannot be used in subclassessuper.getNameBecause there is no entry in the prototype chain to get the base class method

Within a class, a special type called this dynamically points to the type of the current class. Next, you can see that modelType is Model3 in the following example.

class Car{
    model:string = ""
    set(model:string){
        this.model = model
        return this}}class Model3 extends Car{
    clear(){
        this.model = ""}}const model_3 = new Model3()
const modelType = model_3.set("model 3") // Model3
Copy the code

This can also be used as the type of an argument to a class method

class Rect{
    width:number;
    height:number;

    constructor(w:number,h:number){
        this.width = w;
        this.height = h;
    }

    compareWith(other:this){}}Copy the code

This is different from writing about other things. Rect’s subclass Square’s compareWith method now only accepts subclasses that simply inherit without implementing their own methods or defining their own properties, For example, if length:number = 0 is invoked on the instance, the compareWith method will not accept the Rect instance as an argument

class Square extends Rect{
    length:number = 0
}

const rect = new Rect(12.15)

const square = new Square(12.12)

console.log(square.compareWith(rect))
Copy the code