4

我希望在课堂上B我可以阅读 private fields#a#xof class A。但实际上我只能读取#a,万一访问#x我得到一个错误:

无法从类未声明的对象中读取私有成员 #x

看起来像#xB阴影类似的领域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:同样的问题在俄语中。

4

1 回答 1

1

从这里给一部分

就像它们的公共等价物一样,私有静态方法是在类本身上调用的,而不是类的实例。与私有静态字段一样,它们只能从类声明内部访问。

您将A传递给B方法 doSmth

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 无权访问它。

接下来将B传递给B方法 doSmth

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)

于 2021-03-17T10:33:03.253 回答