whatEverMethod.bind(thisValue) binds this to thisValue.
To understand, we can assume (though not actually) every method call
obj.method(arg0)
to equal to
obj.method.apply(obj, arg0)
where the first argument of .apply explicitly tells: which object I am working on (because likely in the definition of .method you may reference to some this value, such as this.prop0 = 10)
What bind does is very simple: bind a this value to a method call, so that when called, no longer uses the default this value based on environment.
For example:
let obj0 = {a: 1}
let obj1 = {a: 2}
obj0.change = function(value) {
this.a = value;
} // when declared, default environment is obj0, since it is a method of obj0
// Now, explicitly bind `this` inside of obj0.change to obj1
let changeFunc = obj0.change.bind(obj1);
// This creates a function that has `this` set to obj1, which has the format changeFunc(value)
changeFunc(10);
console.log(obj1.a) // should be 10, since it is now operating on obj1 (due to binding)
Therefore,
(Array.prototype.concat.bind(all))(someArr)
// is basically
all.concat(someArr)
// due to having the exactly the same `this` value
The reason why we may want to do this is probably all may not be an array. For example, it might be an array-like object, such as the arguments for functions, which looks like an array, but missing common array methods.
foo(() => {...})or pass a reference to an existing function, e.g.foo(myCallback). This example is using thebind()function to do the latter. But personally I don't see the advantage of usingbind()in this situation; generally arrow functions are clearer with no performance downside (at least nowadays).bind()call isn't a reference to an existing function but returns a new function, but it's the same general idea - using an existing function instead of creating a new one inline.