[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 keyis 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 WeakMapto 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

 

posted @   Zhentiw  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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()
点击右上角即可分享
微信分享提示