Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda