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

163
Views
JavaScript simple call function behavior

I want to ask about call function behavior. I get stuck every time when I try to understand call function.

Can anybody help me to understand what is going on by suggesting implementation of the find method?


Hoge = function (val) {
  this.val = val;
  //console.log("this.val" + this.val);
};

Hoge.prototype.find = function (callback) {
  callback.call(this.val);
};

var h = new Hoge(1);

h.find((o) => { 
  console.log(o);  // expected 1 but undefined
  console.log(o === 1); // expected true but  its false (caz o is undefined)
});

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Function#call's first parameter is the this value. To directly invoke a function, just use parentheses.

callback(this.val);

Hoge = function (val) {
  this.val = val;
};

Hoge.prototype.find = function (callback) {
  callback(this.val);
};

var h = new Hoge(1);

h.find((o) => { 
  console.log(o);
  console.log(o === 1);
});

about 4 years ago · Juan Pablo Isaza Report

0

The first param in call will be the new this you want to use. Then onwards are the params you want to pass.

You are basically not making a lot of use .call here, and if you simply want to use o you can pass null and this.val.

Even simpler, simply invoke the callback function

Hoge = function (val) {
  this.val = val;
  //console.log("this.val" + this.val);
};

Hoge.prototype.find = function (callback) {
  //Both work
  callback.call(null,this.val);
  callback(this.val);
};

var h = new Hoge(1);

h.find((o) => { 
  console.log(o);  // expected 1 but undefined
  console.log(o === 1); // expected true but  its false (caz o is undefined)
});

about 4 years ago · Juan Pablo Isaza Report

0

You're not passing call a thisArg argument. Well, you are, but it's value you want passed to the callback.

Hoge = function(val) {
  this.val = val;
  //console.log("this.val" + this.val);
};

Hoge.prototype.find = function(callback) {
  // callback.call(this.val);
  callback.call(this, this.val); // call wants a "this" argument
  // callback(this.val); // Could just do this instead
};

var h = new Hoge(1);

h.find((o) => {
  console.log(o); // expected 1 but undefined
  console.log(o === 1); // expected true but  its false (caz o is undefined)
});

about 4 years ago · Juan Pablo Isaza 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!