读取外部类的隐藏私有字段
Posted
技术标签:
【中文标题】读取外部类的隐藏私有字段【英文标题】:Read shadowed private field of the outer class 【发布时间】:2021-06-14 15:40:18 【问题描述】:我希望在 B
类内我可以读取 A
类的私有字段 #a
和 #x
。但实际上我只能读取#a
,万一访问#x
会报错:
无法从类未声明的对象中读取私有成员#x
似乎#x
的类B
阴影A
的类似字段。首先,这似乎不合逻辑 - 为什么它以这种方式工作,如果它是故意的,那么它是以这种方式计划的吗?是否可以在 A
实例上读取 #x
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.
【问题讨论】:
【参考方案1】:给here的一份子
与它们的公共等价物一样,私有静态方法在 类本身,而不是类的实例。像私有静态字段一样, 它们只能从类声明内部访问。
你将 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)
【讨论】:
以上是关于读取外部类的隐藏私有字段的主要内容,如果未能解决你的问题,请参考以下文章