Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
How to change object values in a function outside that object, vanilla Javascript

I am trying to change the values of an object using function outside of that object, so that I can access those values later (in yet another objects).

I am new to programming, apologies if there is something wrong in my description or question.

For instance,

let myObject = {
  startTime: '',
  endTime: '',
  newId: '',
    
  set setStartTime (val) {
    this.startTime = val
  }
}
    
stopButton.addEventListener('click', () => {
  const {startTime, endTime, newId} = myObject

  myObject.setStartTime = new Date()
    
})

console.log(myObject.startTime)

So when I console log myObject.startTime - in the console its value is empty. Apparently, because it just logs the initial (unchanged value). Why does this happen, and how can I solve this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

when I console log 'myObject.startTime' - in the console its value is empty

Because your code when it loads at first time will show the initial value of myObject which is empty. After you click on stopButton will change but not log any thing, because console.log(myObject.startTime) outside of function, Solution, put console.log inside of click of stopButton.

var dateNow = null;//declare it globally here
stopButton.addEventListener('click', () => {
  const {startTime, endTime, newId} = myObject

  myObject.setStartTime = new Date()
  dateNow = myObject.setStartTime;//<-- assign it value here
})

console.log(dateNow )//<-- call it outside of function here

if I can use that new value (generated inside a function) outside of that function?

Yes you can, just declare a variable globally (outside of function ) to hold the generated value inside click function; then you can call it outside of it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda