[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 @ 2024-11-25 21:10  Zhentiw  阅读(12)  评论(0)    收藏  举报