返回

理解 JavaScript 中 class 的作用域:从 Public 到 Private

前端

JavaScript 中 class 的作用域

在 JavaScript 中,class 是一种用来创建对象的蓝图,它定义了对象的属性和方法。class 的作用域决定了这些属性和方法在代码中的可见性。

1. Public(公共)

Public 是 JavaScript 中 class 的默认作用域。这意味着该作用域内的属性和方法对所有对象都是可见的,无论是当前对象还是继承该类的其他对象。

class Person {
  constructor(name) {
    this.name = name; // Public property
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`); // Public method
  }
}

const person1 = new Person('John Doe');
person1.greet(); // Output: Hello, my name is John Doe.

2. Private(私有)

Private 是 JavaScript 中 class 的最新作用域。它允许您将属性和方法限制在当前类中,使它们对其他对象不可见。

class Person {
  #name; // Private property

  constructor(name) {
    this.#name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.#name}.`); // Private method
  }
}

const person1 = new Person('John Doe');
person1.greet(); // Output: Hello, my name is John Doe.
console.log(person1.#name); // Error: Cannot access private property

3. Protected(受保护)

Protected 是 JavaScript 中的提案,尚未正式成为标准。它允许您将属性和方法限制在当前类及其子类中,但对其他对象不可见。

class Person {
  #name; // Protected property

  constructor(name) {
    this.#name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.#name}.`); // Protected method
  }
}

class Employee extends Person {
  constructor(name, title) {
    super(name);
    this.title = title;
  }

  work() {
    console.log(`${this.name} is working as a ${this.title}.`);
  }
}

const employee1 = new Employee('Jane Doe', 'Software Engineer');
employee1.greet(); // Output: Hello, my name is Jane Doe.
employee1.work(); // Output: Jane Doe is working as a Software Engineer.

总结

在 JavaScript 中,class 的作用域可以分为 public(公共)、private(私有)和 protected(受保护)。这些作用域决定了属性和方法在代码中的可见性,并影响着类中数据的封装和安全性。

  • Public 属性和方法对所有对象都是可见的。
  • Private 属性和方法仅对当前类中的对象可见。
  • Protected 属性和方法对当前类及其子类中的对象可见。

理解 JavaScript 中 class 的作用域对于编写健壮和可维护的代码非常重要。它有助于您控制数据访问,提高安全性并促进代码的可重用性。