I need a little help when I invoke a private method on my class using hash -> #, I get an error called "Invalid or unexpected token".
So I need to know how I can access private method or what is wrong in my code.
this my code:
class Poligono{
constructor(altura, largura){
this.altura = altura
this.largura = largura
}
get area(){
return this.#calcularArea()
}
#calcularArea() {
return this.altura * this.largura
}
}
let var_poligono = new Poligono(50, 60)
console.log(var_poligono)
and this is an error i get:
c:\Users\Mix\Documents\testes\POO-JS\01-Encapsulamento.js:62 return this.#calcularArea() ^ SyntaxError: Invalid or unexpected token
The code produces no error when running in latest chrome so I guess it is a browser support issue. Check https://caniuse.com/?search=private%20methods
As already mentioned, the error indicates a browser compatibility issue. The compatibility list shows the minimum browser version requirement to use private method:
Run the following snippet, and the result is displayed as 3000.
class Poligono {
constructor(altura, largura) {
this.altura = altura
this.largura = largura
}
get area() {
return this.#calcularArea()
}
#calcularArea() {
return this.altura * this.largura
}
}
let var_poligono = new Poligono(50, 60)
console.log(var_poligono.area)
You may see an error like below when you click on the Run code snippet button:
{
"message": "SyntaxError: private fields are not currently supported",
"filename": "https://s...content-available-to-author-only...s.net/js",
"lineno": 20,
"colno": 24
}
It indicates that your current browser version is not compatible with running private class features.