JavaScript 中 class 的理解

按照 mdn 说法,class 声明创建一个绑定到给定名称的新类。

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  getName() {
    return this.name;
  }

  getAge() {
    return this.age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

在上述代码中,我们声明了一个 Person 类,通过构造函数初始化 name 和 age 属性,以及包含一些方法,class 可以用作一类对象的模板,这种写法可以认为等效于组合寄生式继承。
但是js中 this 指向存在一个问题,与其他语言不同,this 永远指向最后被调用的函数:

const person = new Person("John", 30);
const obj = {}
obj.sayHello = person.sayHello;
obj.sayHello();
// Hello, my name is undefined and I am undefined years old.

因为在这里, sayHello 方法里的 this 指向的是 obj 这个空对象,在 js 中可以用 bind 解决这一问题

constructor(name, age) {
  this.name = name;
  this.age = age;
  this.sayHello = this.sayHello.bind(this);
}
posted @ 2025-07-23 19:07  弹道偏左  阅读(10)  评论(0)    收藏  举报