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
标签:About,Javascript,const,log,Object,module,value,key,console From: https://www.cnblogs.com/Answer1215/p/18568756