How do I return the property of a class to an object of a function?

Asked

Viewed 37 times

-2

class Servidor{
    constructor(ip, port){
        this.ip = ip
        this.port = port
        this.admin = true
    }
    getPropert(){
        return { // o erro está aqui
            this.port,
            this.admin,
            this.ip
        }
    }
}

My goal was to do the job getPropert return an object with the value of class properties, however, I come across the following error:

   this.port, 
 SyntaxError: Unexpected token '.'
  • in place of self.id place this.ip and consequently in others.

  • Okay, I’ll do it.

  • I observed here, it was not to be self even, yet even with this, which refers to classse, it gives syntax error.

  • I believe it’s some kind of scope problem, but I can’t solve it.

  • is this to have scope in class and lacked return {'ip' : this.id} or {...this}, creating an object without keys he is complaining ...

  • thank you very much, I got by your comment.

  • recommended reading: https://answall.com/questions/201984/javascript-diff%C3%A7a-entre-this-e-self

  • I will read, thank you very much.

Show 3 more comments

1 answer

1


In addition to changing self for this (class scope) the items in your construtor the method getPropert is to return an object, and object in has key and value and in case the question only has precise value put:

{'ip': this.ip, 'port': this.port, 'admin': this.admin}

or

{...this}

Minimal example:

class Servidor{
    constructor(ip, port){
        this.ip = ip
        this.port = port
        this.admin = true
    }   
    
    getPropert() {
      return {
        'ip': this.ip,
        'port': this.port,
        'admin': this.admin
      };
      // ou
      // return {...this}
    }
}

console.log(
  (new Servidor('192.168.0.1', 80)).getPropert()
);

Another explanation of self and this: Javascript - Difference between `this` and `self`

  • 1

    Thank you very much, solved the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.