Home > Blockchain >  Private method JavaScript
Private method JavaScript

Time:06-09

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

CodePudding user response:

The code produces no error when running in latest chrome so I guess it is a browser support issue. Check version requirement

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)

  • Related