I am trying to make a stack and queue classes, but I cant make the data field private without not being able to use inheritance. I get an Uncaught SyntaxError: Private field '#data' must be declared in an enclosing class error every time I try. how can I have the subclasses inherit the private field? code below:
class Datalist {
#data
constructor() {
this.#data = Array.from(arguments)
return this.#data
}
valueOf() {
return this.#data
}
get size() {
return this.#data.length
}
peek() {
if (this.size > 0) {
return this.#data[0]
} else {
return null
}
}
}
class Queue extends Datalist {
constructor() {
super(arguments)
}
enqueue() {
this.#data = this.#data.concat(arguments)
}
dequeue() {
return this.#data.shift()
}
}
class Stack extends Datalist {
constructor() {
super(arguments)
this.#data = this.#data.reverse()
}
push() {
this.#data = this.#data.splice(0, 0, Array.from(...arguments).reverse)
}
pop() {
return this.#data.shift()
}
}
A possible workaround which keeps the approach of extended classes and prototypal methods together with private fields and protected data could be based on
WeakMapbecause one can take advantage of working with a single shared reference for each instantiation regardless of the actual inheritance.