javascript - JavaScript 私有(private)字段是按类还是按实例私有(private)的?

标签 javascript oop

JavaScript 最近添加了私有(private)类字段,以散列前缀命名。

( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields )

我正在寻找关于这种形式的隐私是“按类”还是“按实例”的明确答案。

假设一个 Person 类定义了一个名为“#secret”的私有(private)字段。

我使用“new”构造了 Person 类的两个实例:person1 和 person2。

person1 是否有权检查和修改 person2 的#secret 字段?

class Person {
  #secret;
  constructor(secret) {
    this.#secret = secret;
  }
  getSomebodyElsesSecret(somebody) {
    return somebody.#secret;
  }
  setSomebodyElsesSecret(somebody, value) {
    somebody.#secret = value;
  }
}

最佳答案

它们是按类的 - 一个实例可以查看和修改另一个实例。

class Person {
  #secret;
  constructor(secret) {
    this.#secret = secret;
  }
  getSomebodyElsesSecret(somebody) {
    return somebody.#secret;
  }
  setSomebodyElsesSecret(somebody, value) {
    somebody.#secret = value;
  }
}

const a = new Person('a');
const b = new Person('b');
console.log(a.getSomebodyElsesSecret(b))
a.setSomebodyElsesSecret(b, 'c');
console.log(a.getSomebodyElsesSecret(b))

一种看待它的方法是,私有(private)字段类似于仅限于类范围的变量 - 它们可以被类的 {} 中的任何内容引用>,并且不能被外部引用。

就范围而言,它有点像定义私有(private)变量的 WeakMap 和返回类的 IIFE:

const Person = (() => {
    const secrets = new WeakMap();
    return class Person {
        constructor(secret) {
            secrets.set(this, secret);
        }
        getSomebodyElsesSecret(somebody) {
            return secrets.get(somebody);
        }
        setSomebodyElsesSecret(somebody, value) {
            secrets.set(somebody, value);
        }
    }
})();

const a = new Person('a');
const b = new Person('b');
console.log(a.getSomebodyElsesSecret(b))
a.setSomebodyElsesSecret(b, 'c');
console.log(a.getSomebodyElsesSecret(b))

关于javascript - JavaScript 私有(private)字段是按类还是按实例私有(private)的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71580410/

相关文章:

javascript - 引用要在 javascript 中扩充的对象

php - $this 的范围在 PHP 中是 funked 是错误还是功能?

javascript - 如何更新混淆代码中的变量

javascript - jQuery:我看到了append、prepend、appendTo,那么取出内容呢?

javascript - Angular JS - UI路由器页面重新加载不会设置状态

c# - 获取用户在 Asp.Net 和 javascript 中花费的 onunload 时间

Python键入TypeVar(A,B,covariant = True)是什么意思?

javascript - Google 自动完成器位置在 Angular 2 的子组件中不起作用

javascript - 有没有办法在保持像素大小的同时缩放 p5js 草图?

php - 已超出数据库中的 'max_questions' 资源