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

144
Vistas
What does this JavaScript code return for bar, baz, and biz function calls?

Learning JavaScript Fundamentals, confused on what the function calls return. I have an idea of f.bar returns 7 because when the f object is created it gets access to functions of Foo that have the "this" keyword. Also I believe f.baz returns an error because this function is only available locally and does not use the "this" keyword which makes it unavailable outside Foo. f.biz I am confused but I do know the Prototype keyword allows for inheritance of Foo properties.

An explanation for each function call would be awesome, thank you everyone!

var Foo = function(a){

  this.bar = () => {
    return a; 
  }

  var baz = function(){
    return a;
  }

  Foo.prototype = {
    biz: () => {
      return this.bar();
    }
  }

}

var f = new Foo(7);

f.bar();// what does this return?
f.baz(); // what does this return?
f.biz(); // what does this return?

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

As it is now, only the bar function will work as intended.

The baz function is in a local variable, so it's only accessible inside the Foo function as baz but not as this.baz (variables and instance properties (this.whatever) are not connected in any way).

The case of biz is a bit more complicated. Normally, that's more or less how you'd create a prototype method, but you did it in the wrong place. It should be outside the function, because the way it is now, it's:

  • reassigned on every call of new Foo() (unnecessary)
  • assigned only after the current instance is created, so it will take effect only on the next instance (also if you used a in it (which you shouldn't), you'd find that it always has the a of the previous call)

You also don't want to use an arrow function when you want to "let JS set this" (arrow functions copy their this from where they were defined).

So, to make biz work, you have to do this:

var Foo = function(a){

  this.bar = () => {
    return a; 
  }

}

Foo.prototype = {
  biz: function (){
    return this.bar();
  }
}


var f = new Foo(7);

console.log(f.bar());
console.log(f.biz()); 

about 4 years ago · Santiago Gelvez Denunciar
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