How to change a value of a literal JavaScript object?

1

I'm trying to change the value of a property in a JavaScript object, but in object creation literally, not constructor.

var cliente = {
  nome: "Wesley",
  idade: 20,
  cargo: "Front End",
  setAtualiza : functiion(n, i, c){
    this.nome = n;
    this.idade = i;
    this.cargo = c
  }
};

setAtualiza("NovoNome", 25, "Pleno");
for(var x in cliente){
  console.log(cliente[x]);
};

setAtualiza();

And the output I'd like to have is: "NewName 25 Full"

What am I doing wrong? Or this can not be done (refresh a literal object).

    
asked by anonymous 13.04.2015 / 19:50

3 answers

5

In addition to a typo you are calling a function that does not exist globally, it only exists in the context of the client object, so you should call it through the object.

var cliente = {
  nome: "Wesley",
  idade: 20,
  cargo: "Front End",
  setAtualiza : function(n, i, c){ //tinha um erro de digitação aqui.
    this.nome = n;
    this.idade = i;
    this.cargo = c
  }
};

cliente.setAtualiza("NovoNome", 25, "Pleno"); //a chamada deve ser contextual
for(var x in cliente){
  document.body.innerHTML += (cliente[x]); //mudei aqui só executar certo no SO, pode manter o seu
};
    
13.04.2015 / 19:57
5

Function is spelled incorrectly and to call a method you need a reference to the object in question. In this case this reference can be accessed through the client variable. Here is the code block changed:

var cliente = {
  nome: "Wesley",
  idade: 20,
  cargo: "Front End",
  setAtualiza : function(n, i, c){
    this.nome = n;
    this.idade = i;
    this.cargo = c
  }
};

cliente.setAtualiza("NovoNome", 25, "Pleno");
for(var x in cliente){
  console.log(cliente[x]);
};
    
13.04.2015 / 19:58
4

The function was missing on the object itself, as a method . The way you did it must be giving an error because the function does not exist outside the object. In code, I mean this:

cliente.setAtualiza("NovoNome", 25, "Pleno");
//  ˆ---- faltou isto!
    
13.04.2015 / 19:57