[Javascript] About private access (Object.getOwnPropertySymbols)
We have a module:
const key = Symbol('key')
export class A {
[key] = 1
value () {
console.log(this[key])
}
}
It seems that key
is not expose to outside of module, but still we are able to get it.
import {A} from './module.js'
const a = new A()
const keys = Object.getOwnPropertySymbols(a)
console.log(keys) //[Sybmol(key)]
const key = keys[0]
console.log(a[key])
And we know that since ES2022 we have true private field in class:
// module.ts
export class A {
#key = 1
value () {
console.log(this.#key)
}
}
This should work, but it has browser compabilities issue.
What we can do is using a WeakMap
to stroe all the private field & value, refer to current instance
const privateField = new WeakMap()
export class B {
constructor() {
privateField.set(this, {key: 'value'})
}
key () {
console.log(privateField.get(this).key)
return privateField.get(this).key
}
}
import { B } from './module.js'
const b = new B()
console.log(b.key()) //value
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-11-25 [Typescript] 116. Hard - Split
2022-11-25 [Typescript] 115. Hard - Drop String
2019-11-25 [ARIA] aria-describedby & aria-labelledby
2019-11-25 [Security] Always use parameterized queries
2016-11-25 [Ramda] Handle Branching Logic with Ramda's Conditional Functions
2016-11-25 [Angular2 Router] Setup page title with Router events
2015-11-25 [Redux] Store Methods: getState(), dispatch(), and subscribe()