Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

318
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda