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

315
Views
Polyfill for bind includes using call or apply, why?

The polyfill of bind which I find online is something like -

Function.prototype.bind = function(obj, ...args) {
  const self = this;
  return function(...args2) {
    return self.apply(obj, [...args, ...args2]);
  };
}

where we use call/apply to call the function.

My question is why not simplify it to be

Function.prototype.myBind = function (obj, ...args) {
  obj.func = this;
  return function (...params) {
    return obj.func(...args, ...params)
  }
};

because internally both call and apply assign the function to the object and then execute it.

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

0

By doing

obj.func = this;

you are mutating the object passed in. .bind does not do such a thing, and it's almost always a good idea not to mutate objects that you don't "own" (that is, are only used by your own internal code).

It would be quite strange for a call to .bind result in a mutation of an object which may be completely unrelated to the caller, eg:

Function.prototype.myBind = function (obj, ...args) {
  obj.func = this;
  return function (...params) {
    return obj.func(...args, ...params)
  }
};

const obj = {
  foo: 'foo'
};

function fn() {
  console.log(this);
}
const boundFn = fn.myBind(obj);
console.log(Object.keys(obj));

It's much safer and predictable to avoid side effects and keep the bound function inside .bind's closure than to set it on an external object which isn't expecting a new property to suddenly appear on it.

As for the title:

Polyfill for bind includes using call or apply, why?

IIRC, .bind was introduced in ES5. But .apply exists in ES3 too, and since basically all environments anyone uses are at least ES3, using .apply to polyfill .bind is safe. (though. using spread/rest syntax is not, since that's ES2015)

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!