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

145
Visualizações
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 Respostas
Responde à pergunta

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 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