Problem with Get, Set javascript

Asked

Viewed 49 times

1

Could someone tell me how I do a set of an MVC Javascript class? I send, but every time I search the value to check it gets Undefined. Follow example:

charController.js:

class CharController {

  constructor() {

    this._charNameSelected;
    this.initialize();

  }

  get charNameSelected() {
    return this._charNameSelected;
  }

  set charNameSelected(value) {
    this._charNameSelected = value;
  }


  initialize() {

    console.log(this.charNameSelected);

  }
}

charModel.js:

objCharController = new CharController();
objCharController.charNameSelected = "teste";
  • Put the code, not the image.

  • Okay, I’m new here, thanks for the tip.

1 answer

1

I’m not sure what you mean by "a Javascript MVC class", but the problems you have in your example are the method initialize runs before of your set, and therefore the console.log gives Undefined. If you run the initalize then you will see that everything is in order (see the example below).

class CharController {
  constructor() {
    this._charNameSelected;
    this.initialize();
  }

  get charNameSelected() {
    return this._charNameSelected;
  }

  set charNameSelected(value) {
    this._charNameSelected = value;
  }
  initialize() {
    console.log(this.charNameSelected);
  }
}

objCharController = new CharController();
objCharController.charNameSelected = "teste";
objCharController.initialize();

What you probably want to do is make arguments to that constructor and thus assign a value before the initialize run. Then it would be like this:

class CharController {
  constructor(name) {
    this._charNameSelected = name; // aqui podias usar `charNameSelected` se quiseres invocar a logica do 'setter'
    this.initialize();
  }

  get charNameSelected() {
    console.log('get');
    return this._charNameSelected;
  }

  set charNameSelected(value) {
    console.log('set =>', value);
    this._charNameSelected = value;
  }
  initialize() {
    console.log('initialize =>', this.charNameSelected);
  }
}

objCharController = new CharController('teste');
console.log(objCharController.charNameSelected);

  • Thank you very much!

  • @Brunobafilli if the answer was what you were looking for you can mark as accepted. I’m glad I helped.

Browser other questions tagged

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