Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
Property of object not returning the expected value in Javascript

I am new to javascript and was trying to create a stopwatch object as described in a youtube video. Following is the code:

function Stopwatch(){
    let durationVal = 0;
    let startFlag = 0;

    this.start = function(){
            if (startFlag === 0){
                    durationVal = Date.now()
                    startFlag = 1;        
            }
            else{
                    throw new Error('Stopwatch is already running')
            }
    }

    this.stop = function(){
            if(startFlag === 1){
                    durationVal = Date.now() - durationVal
                    startFlag = 0;
            }
            else{
                    throw new Error('Stopwatch is not running')
            }
    }

    this.duration = durationVal;

    this.reset = function(){
            durationVal = 0;
    }

}

When I try to create an object and access its duration property

let sw = new Stopwatch()
sw.start()
sw.stop()
console.log(sw.duration)

It returns a zero. However, when I change my javascript to use a method to get the duration value:

 this.duration = function(){
            return durationVal;
 }

it gives the correct value. Can you explain why?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda