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.
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)