Problem with Get, Set javascript

1

Can anyone tell me how I make a set of an MVC Javascript class? I submit, but whenever I redeem the value to check it gets undefined. Here's an 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";
    
asked by anonymous 17.06.2018 / 17:34

1 answer

1

I'm not sure what you mean by "a Javascript MVC class" , but the problems you have in your example is the initialize method before set , and therefore console.log gives undefined. If you run initalize then you will see that everything is in order (see 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 pass arguments to this constructor and thus assign a value before initialize run. In this case it would look 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);
    
18.06.2018 / 00:11