ES6 Private members initialization
by Arnaud Buchholz
JavaScript
class Test {
#array = []
#object = {}
constructor () {
this.ownProperty = performance.now()
}
get array () {
return this.#array
}
addToArray (value) {
this.#array.push(value)
}
get object () {
return this.#object
}
addToObject (name, value) {
this.#object[name] = value
}
toString () {
return `#array: ${this.#array.join(',')}
#object: ${JSON.stringify(this.#object).replaceAll('"', '')}`
}
}
const test1 = new Test()
test1.addToArray(1)
test1.addToObject('test1', 'value1')
console.log('test1', test1.toString())
const test2 = new Test()
test2.addToArray(2)
test2.addToObject('test2', 'value2')
console.log('test2', test2.toString())
console.log(test1.array === test2.array)
console.log(test1.object === test2.object)
console.log(Object.keys(test1))
console.log('test1 owns object', test1.hasOwnProperty(test1))
console.log('Test.prototype owns object', Test.prototype.hasOwnProperty(test1))
console.log(Test.prototype.object)