typescript中this关键字与解构赋值_ES6

解构赋值

这是一个 JavaScript ES6(ECMAScript 2015)特性,允许你从一个对象或数组中提取值,并赋值给独立的变量。

this关键字

在 TypeScript(以及 JavaScript)中,this 关键字主要用于引用当前对象的实例。它常用于类的方法内部,以访问或修改该对象的属性或方法。以下是一个简单的例子:

class Person {  
    name: string;  
    age: number;  
  
    constructor(name: string, age: number) {  
         = name;  
        this.age = age;  
    }  
  
    introduce() {  
        console.log(`Hello, my name is ${} and I am ${this.age} years old.`);  
    }  
}  
  
let person = new Person("Alice", 25);  
person.introduce();  // 输出: Hello, my name is Alice and I am 25 years old.

在这个例子中, 和 this.age 分别引用了当前 Person 实例的 name 和 age 属性。在 introduce 方法中,我们使用 this 关键字来访问这些属性。

需要注意的是,this 的值在函数被调用时确定,而非函数被创建时。在 TypeScript(和 JavaScript)中,函数的调用方式会影响 this 的值。例如,如果你把一个对象的方法赋值给一个变量,并直接调用这个方法,那么 this 将不会引用原来的对象。这是因为在 JavaScript 和 TypeScript 中,函数的 this 值取决于函数的调用方式,而不是函数被定义的位置。

值得注意:如果你在使用回调函数,Promises,或者任何异步代码,你需要特别小心 this 的上下文,因为在这些情况下,this 的值可能会发生变化。你可以使用 .bind().call() 或 .apply() 方法来显式地设置 this 的值。

另外,如果你在类的外部或者没有明确的对象上下文中使用 this,例如在全局作用域或者一个普通的函数中,this 通常会指向全局对象(在浏览器中是 window,在 Node.js 中是 global),或者在严格模式下('use strict';),this 会是 undefined。所以在这些情况下使用 this 需要特别小心。

语句“const { point, game } = this”如何理解?

在 TypeScript(以及 JavaScript)中,const { point, game } = this; 是一个解构赋值语句,它用于从 this 对象中提取 point 和 game 属性,并将它们分别赋值给同名的常量。

这里是对这个语句的逐步解释:

  1. 根据前面介绍,解构赋值是一个 JavaScript ES6(ECMAScript 2015)特性,允许你从一个对象或数组中提取值,并赋值给独立的变量。
  2. 从对象中提取属性:在这个例子中,{ point, game } 表示我们想要从 this 对象中提取 point 和 game 这两个属性。
  3. this 关键字:在类的方法中,this 通常引用当前类的实例。所以,const { point, game } = this; 是从当前类的实例中提取 point 和 game 属性。
  4. 创建常量const 关键字用于创建常量,即它们的值在初始化后不能再被改变。

所以,整个语句的含义是:从当前类的实例(this)中提取 point 和 game 属性,并将它们分别赋值给 point 和 game 常量。之后,你就可以直接使用 point 和 game 这两个常量,而不需要通过 this.point 或 this.game 来访问它们。

这里是一个简单的示例来说明这个概念:

class GameClass {  
    point: number;  
    game: string;  
  
    constructor(point: number, game: string) {  
        this.point = point;  
        this.game = game;  
    }  
  
    displayInfo() {  
        const { point, game } = this;  
        console.log(`The point is ${point} and the game is ${game}.`);  
    }  
}  
  
const gameInstance = new GameClass(10, "Chess");  
gameInstance.displayInfo();  // 输出: The point is 10 and the game is Chess.

在这个例子中,displayInfo 方法内部使用了解构赋值来从 this 中提取 point 和 game 属性,并直接使用了这些提取出来的值。