ReasonJun

Typescript : Explicit this 본문

Frontend/Typescript

Typescript : Explicit this

ReasonJun 2023. 6. 10. 12:47
728x90

In TypeScript, the this keyword is used to refer to the current instance of an object or class within a method or function. It represents the context in which a function is called or an object is accessed.

 

The behavior of this can vary depending on the context in which it is used. Let's explore some common scenarios:

  • In Object Methods:

When this is used inside a method of an object, it refers to the object itself. This allows you to access other properties and methods of the same object using this.propertyName or this.methodName.

const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, ${this.name}!`);
  },
};

person.greet(); // Output: Hello, John!
  • In Function Callbacks:

The behavior of this in function callbacks depends on how the function is called. By default, this refers to the global object (window in browsers, or global in Node.js). However, if you use arrow functions (() => {}), this will be lexically scoped and retain the context of the enclosing scope.

const person = {
  name: 'John',
  greet: function() {
    setTimeout(() => {
      console.log(`Hello, ${this.name}!`);
    }, 1000);
  },
};

person.greet(); // Output (after 1 second): Hello, John!

In the above example, using an arrow function inside the setTimeout callback preserves the this context of the person object, allowing access to the name property.

  • In Class Methods:

In TypeScript classes, this is used within class methods to refer to the current instance of the class. It allows access to other properties and methods of the class using this.propertyName or this.methodName.

class Person {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}!`);
  }
}

const john = new Person('John');
john.greet(); // Output: Hello, John!

In class methods, this refers to the instance of the class created using the new keyword. It provides access to the instance-specific properties and methods.

 

It's important to note that the behavior of this can be influenced by how a function is called, such as with call(), apply(), or bind(), which allow you to explicitly set the this context.

728x90

'Frontend > Typescript' 카테고리의 다른 글

Typescript : Class & Access Modifiers  (2) 2023.06.10
Typescript : Overloading  (0) 2023.06.10
Typescript : Optional / Readonly Attribute in Interface  (0) 2023.06.10
Typescript : Interface  (0) 2023.06.10
Typescript : Type Guard  (0) 2023.06.10
Comments