Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!