JS中private protected public readonly的区别

在JavaScript中,不像在TypeScript或其他一些静态类型语言中那样有内置的privateprotectedpublicreadonly关键字来明确地声明成员的访问级别和可变性。然而,我们可以通过一些约定和模式来模拟这些概念。

Private

private成员在类外部是不可访问的。在JavaScript中,我们可以通过闭包或使用#(私有字段)来模拟私有属性。

function Person(name) {
  var privateName = name; // 私有属性

  this.getName = function() {
    return privateName;
  };
}

var person = new Person('Alice');
console.log(person.getName()); // 输出 'Alice'
console.log(person.privateName); // 输出 undefined
使用私有字段(#):
class Person {
  #name; // 私有字段

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

  getName() {
    return this.#name;
  }
}

const person = new Person('Alice');
console.log(person.getName()); // 输出 'Alice'
console.log(person.#name); // 报错,私有字段不能在类外部访问

Protected

protected成员在类及其子类中是可访问的,但在类外部不可访问。在JavaScript中,我们可以通过约定来模拟受保护的属性,通常是通过以下划线_前缀命名。

class Person {
  _name; // 受保护的属性

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

  getName() {
    return this._name;
  }
}

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

  getDetails() {
    return `${this._name},${this._title}`;
  }
}

const employee = new Employee('Alice', 'Developer');
console.log(employee.getDetails()); // 输出 'Alice, Developer'
console.log(employee._name); // 不推荐,但技术上可以访问

Public

public成员可以在任何地方被访问,这是JavaScript中的默认行为。

class Person {
  name; // 公共属性

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

  getName() {
    return this.name;
  }
}

const person = new Person('Alice');
console.log(person.getName()); // 输出 'Alice'
console.log(person.name); // 输出 'Alice'

Readonly

readonly成员在初始化后不能被修改。在JavaScript中,我们可以通过使用Object.defineProperty来模拟只读属性。

class Person {
  constructor(name) {
    Object.defineProperty(this, 'name', {
      value: name,
      writable: false, // 设置为只读
      enumerable: true,
      configurable: true
    });
  }
}

const person = new Person('Alice');
console.log(person.name); // 输出 'Alice'
person.name = 'Bob'; // 不会报错,但不会改变值
console.log(person.name); // 仍然输出 'Alice'

请注意,这些模式并不提供真正的访问控制,它们更多是约定和文档的辅助,以指导开发者如何使用类和对象。在ES6及更高版本中,私有字段(#)提供了一种更接近真正私有的特性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值