javascript - 读取外部类的阴影私有(private)字段

标签 javascript private ecmascript-2021

我希望在类(class)内B我可以读取私有(private)字段 #a#x类(class)A .但实际上我只能读取#a , 万一访问 #x我收到一个错误:

Cannot read private member #x from an object whose class did not declare it


好像#x类(class)B A的阴影相似场.首先,这似乎不合逻辑 - 为什么它会以这种方式工作,如果它是故意的,那么它是以这种方式计划的吗?是否可以阅读 #xA实例在 B 内?

class A {
  #a = "A#a"
  #x = "A#x"

  static B = class B {
    #b = "B#b"
    #x = "B#x"

    static doSmth(obj) {
      try { console.log(obj.#a) } catch (e) { console.log(e.message) }
      try { console.log(obj.#b) } catch (e) { console.log(e.message) }
      try { console.log(obj.#x) } catch (e) { console.log(e.message) }
    }
  }
}

console.log("=== A ===")
A.B.doSmth(new A)
console.log("")
console.log("=== B ===")
A.B.doSmth(new A.B)
.as-console-wrapper.as-console-wrapper { max-height: 100vh }
.as-console-row.as-console-row:after { content: none }

如果重要的话,我正在使用 Google Chrome 89.0.4389.90。
PS:Same question in Russian.

最佳答案

赠送一部分来自 here

Like their public equivalent, private static methods are called on the class itself, not instances of the class. Like private static fields, they are only accessible from inside the class declaration.


您通过 一个 进入 方法论
A.B.doSmth(new A)

A#a
Cannot read private member #b from an object whose class did not declare it
Cannot read private member #x from an object whose class did not declare it
方法无权访问 A#x,因为 B#x 也声明了,而 A 无权访问它。
接下来你通过进入 方法论
A.B.doSmth(new A.B)

Cannot read private member #a from an object whose class did not declare it
B#b
B#x
方法 B 无法访问 A#а

class A {
  #a = "A#a"
  #b = "A#b"
  #x = "A#x"
  
  static doSmthA(obj) {
      try { console.log(obj.#a) } catch (e) { console.log(e.message) }
      try { console.log(obj.#b) } catch (e) { console.log(e.message) }
      try { console.log(obj.#x) } catch (e) { console.log(e.message) }
  }

  static B = class B {
    
    #a = "B#a"
    #b = "B#b"
    #x = "B#x"

    static doSmthB(obj) {
      try { console.log(obj.#a) } catch (e) { console.log(e.message) }
      try { console.log(obj.#b) } catch (e) { console.log(e.message) }
      try { console.log(obj.#x) } catch (e) { console.log(e.message) }
    }
  }
}

console.log("=== A ===")
A.doSmthA(new A)
console.log("")
console.log("=== B ===")
A.B.doSmthB(new A.B)

console.log("=== NEXT ===")

console.log("=== A ===")
A.doSmthA(new A.B)
console.log("")
console.log("=== B ===")
A.B.doSmthB(new A)

关于javascript - 读取外部类的阴影私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66670747/

相关文章:

c++ - 我可以转换对象并访问 C++ 中的私有(private)数据成员吗?

javascript - JavaScript 中整数的千位分隔符

javascript - 质数 JavaScript

javascript - 验证 Wysiwyg 字段

javascript - 无法使用带有 uri 的 React Native 显示图像

C++ 设置私有(private)数组的值

c++ - 我可以禁止从基类调用派生类的私有(private)成员吗?

javascript - 在箭头函数上运行 eslint 时报告意外 token "="

javascript - Flow 不支持某些 JavaScript (ECMAScript) 内置方法,我该怎么办?

node.js - 顶级等待是否有超时?