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

252
Views
JS Function.prototype.apply() explanation

I'm a bit confused about this example:

Function.prototype.defer = function(ms) {
  let f = this; // I know content of this - it is function f
  return function(...args) {
    setTimeout(() => f.apply(this, args), ms);
  }
};

// check it
function f(a, b) {
  alert( a + b );
}

f.defer(1000)(1, 2);

I know that first this (let f) contains function f, but what about this in returned function? It is undefined as I understand, isn't it (f.apply(undefined, args)) ? If so, why should we use apply and why does it work?

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

0

It is undefined as I understand

It is in your example use of of it.

why should we use call and why does it work?

Not sure why you mention call. Maybe you intended apply. The reason is that you don't know know what f is and whether it needs some this binding, which depends on how it is called. It is nice to take that into account and not lose the this binding in the deferred execution.

Here is an example where the user of defer wants to use this:

Function.prototype.defer = function(ms) {
  let f = this;
  return function(...args) {
    setTimeout(() => f.apply(this, args), ms);
  }
};

// check it
function f(a, b) {
  console.log(this + a + b );
}

f.defer(1000).call(3, 1, 2); // 6

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!