TypeScript 中 this 关键字的用途是什么?

typescriptserver side programmingprogramming更新于 2025/10/9 12:22:17

"this"关键字是 TypeScript 中最常用的关键字之一。对于 TypeScript 初学者来说,理解 this 关键字的工作原理比较复杂,但在本教程结束后,他们就能学会。在本教程中,我们将学习如何在 TypeScript 中使用 this 关键字。

语法

用户可以按照以下语法来大致了解 this 关键字的使用方法。用户可以观察如何使用 this 关键字访问变量或调用方法。

this.var_name;
this.method_name();
console.log(this.var_name);

在 TypeScript 中,如果 this 关键字未在任何类或方法中使用,则它指向全局对象。即使在函数内部使用 this 关键字,它也指向全局对象,即 window 对象。我们也可以在类方法的回调函数中使用 this 关键字。

下面,我们将学习如何在不同的场景中使用 this 关键字。

示例 1

在下面的示例中,我们创建了 demo 类,它包含"y"属性。此外,我们在 demo 类中定义了 display() 方法。display() 方法会打印包含属性 y 值的消息。这里,重要的是我们使用 this 关键字访问属性 y。在 display() 方法中,this 关键字指向 demo 类。

之后,我们创建了 demo 类的对象,并通过将 demo_object 作为引用来调用 display() 方法,该方法会打印输出中显示的消息。

// 创建 demo 类
class demo {
   y = 10;
   // 在 demo 类中定义 display 方法
   display() {
      console.log("This is display method of demo class ");
      console.log("The Value of the Property y of the demo class is " + this.y)
   }
}
// 创建演示类的对象
var demo_object = new demo();

// 调用demo类的对象
demo_object.display();

编译后,将生成以下 JavaScript 代码 -

// 创建演示类
var demo = /** @class */ (function () {
   function demo() {
      this.y = 10;
   }
   // 在 demo 类中定义 display 方法
   demo.prototype.display = function () {
      console.log("This is display method of demo class ");
      console.log("The Value of the Property y of the demo class is " + this.y);
   };
   return demo;
}());
// 创建 demo 类的对象
var demo_object = new demo();

// 调用 demo 类的对象
demo_object.display();

输出

以上代码将产生以下输出 -

This is display method of demo class
The Value of the Property y of the demo class is 10

我们将在下一个示例中遵循以下步骤 -

  • 步骤 1 - 创建 Vehicle 类,其中包含 Vehicle_type 属性和 show_type() 类方法。

  • 步骤 2 - 在 show_type() 方法中,使用此关键字访问车辆类型并将其与消息一起打印。

  • 步骤 3 - 创建 car 类,该类扩展了 Vehicle 类。这意味着 car 是基类,而 Vehicle 是父类。这里,car 类是 Vehicle 类的基类,这意味着 Vehicle 类的所有方法和属性都被虚拟复制到了 car 类,我们也可以使用 car 类的对象来访问它。

  • 步骤 4 − 使用 this 关键字定义 show_message() 方法,该方法调用 car 类的 show_type() 方法。

示例 2

在本例中,this 关键字指的是 car 类。由于 show_type() 被虚拟复制到了 car 类,我们可以使用此关键字来访问它。简单来说,我们使用此关键字将父类的方法访问到了子类。

// 创建 Vehicle 类
class Vehical {

    // 定义 Vehicle_type 属性
    Vehicle_type: string = "medium";
    
    // Vehicle 类的 Show_type 方法。
   show_type() {

      console.log("This is inside the show_type method of the Vehicle class");
      console.log("The vehicle type is " + this.vehicle_type);
   }
}
// 创建 car 类,它是 Vehicle 类的基类。
class car extends Vehical {

	// 在 car 类中定义 display 方法
   show_message() {
      this.show_type();
      console.log("This is show_message method of car class ");
   }
}
// 创建 car 类的对象
var car_object = new car();
// 调用 demo 类的对象
car_object.show_message();

编译后,它将生成以下 JavaScript 代码 -

var __extends = (this && this.__extends) || (function () {
   var extendStatics = function (d, b) {
      extendStatics = Object.setPrototypeOf ||
      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
      function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
      return extendStatics(d, b);
   };
   return function (d, b) {
      extendStatics(d, b);
      function __() { 
         this.constructor = d; 
      }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
   };
})();
// 创建车辆类
var Vehical = /** @class */ (function () {
    function Vehical() {
        // 定义vehicle_type属性
        this.vehicle_type = "medium";
    }
    // Vehicle类的Show_type方法。
   Vehical.prototype.show_type = function () {
      console.log("This is inside the show_type method of the Vehicle class");
      console.log("The vehicle type is " + this.vehicle_type);
   };
   return Vehical;
}());
// 创建汽车类,它是车辆类的基类。
var car = /** @class */ (function (_super) {
   __extends(car, _super);
   function car() {
      return _super !== null && _super.apply(this, arguments) || this;
   }
   // 在汽车类中定义显示方法
   car.prototype.show_message = function () {
      this.show_type();
      console.log("This is show_message method of car class ");
   };
   return car;
}(Vehical));
// 创建 car 类的对象
var car_object = new car();

// 调用 demo 类的对象
car_object.show_message();

输出

以上代码将产生以下输出 -

This is inside the show_type method of the Vehicle class
The vehicle type is medium
This is show_message method of car class

示例 3

在本例中,我们用 TypeScript 创建了一个普通对象。我们在对象内部定义了 website_name 和 language 属性。此外,我们还定义了 test() 方法,该方法返回字符串。

在 test() 方法中,我们使用 this 关键字访问对象属性。这里,this 关键字指向当前对象。之后,我们调用 test() 方法,将 obj 作为引用并存储字符串,该方法将该字符串返回给 message 变量。

var obj = {
    // 定义对象属性
    website_name: "TutorialsPoint",
    language: "TypeScript",
    
    // 定义对象的 test() 方法
   test(): string {
      return (
         this.website_name +
         " is a best website to learn " +
         this.language +
         " Programming language."
      );
   },
};
// 调用 obj 的 test() 方法并将返回值存储到 message 中。
let message: string = obj.test();

// 打印消息
console.log(message);

编译后,它将生成以下 JavaScript 代码 -

var obj = {
    // 定义对象属性
    website_name: "TutorialsPoint",
    language: "TypeScript",
    
    // 定义对象的 test() 方法
   test: function () {
      return (this.website_name +
      " is a best website to learn " +
      this.language +
      " Programming language.");
   }
};
// 调用 obj 的 test() 方法并将返回值存储到 message 中。
var message = obj.test();

// 打印消息
console.log(message);

输出

以上代码将产生以下输出 -

TutorialsPoint is a best website to learn TypeScript Programming language.

示例 4

在下面的示例中,我们创建了测试类并定义了月份的数字数组。之后,我们使用 filter() 方法过滤所有大于 7 的月份。我们将回调函数作为 filter() 方法的第一个参数,并将 this 关键字作为第二个参数。

我们在 filter() 方法的回调函数中使用 this 关键字访问了类的 value 属性。我们可以从这个示例中学习如何在回调函数中使用 this 关键字。

// 创建测试类
class test {

// 定义 value 属性
value: number = 7;

// 定义月份数组
months: Array<number> = [1, 4, 7, 10, 12, 6, 9];

// 过滤所有大于 7 的月份
// 使用此关键字作为方法的参数
filtered_months = this.months.filter((month) => {
    return month > this.value;
}, this);
}
// 创建测试类的对象
let test_obj = new test();
console.log("Filtered months are " + test_obj.filtered_months);

编译后,它将生成以下 JavaScript 代码 -

// 创建测试类
var test = /** @class */ (function () {
    function test() {
        var _this = this;
        
        // 定义 value 属性
        this.value = 7;
        
        // 定义 months 数组
        this.months = [1, 4, 7, 10, 12, 6, 9];
        
        // 过滤所有大于 7 的月份
        // 使用 this 关键字作为方法的参数
      this.filtered_months = this.months.filter(function (month) {
         return month > _this.value;
      }, this);
   }
   return test;
}());
// 创建测试类的对象
var test_obj = new test();
console.log("过滤后的月份为 " + test_obj.filtered_months);

输出

上述代码将产生以下输出 -

过滤后的月份为 10,12,9

在本教程中,我们学习了四个在 TypeScript 中使用 this 关键字的不同示例。"this"关键字指向我们使用的对象或类。虽然我们可以将 this 关键字用作全局对象,但这并不是好的做法。因此,建议在特定作用域内(例如对象或类)使用此关键字。


相关文章