Today I continued to study the implementation of bind function and also learned the statements of shim and polyfill. Let’s summarize it now.
if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; };}This is an implementation in the official document. I will talk about what I want to say in two aspects.
The first is the parameter, the use of agruments
var aArgs = Array.prototype.slice.call(arguments, 1), here is to take out the parameter array of bind function. The first parameter does not (that is, do not oThis), which is the object to be bound to the method, and the second is
aArgs.concat(Array.prototype.slice.call(arguments))); Here we use the array method, insert the parameters behind the parameter array. Note that this function is returned and executed. Its parameter array is the parameter array of the fBound function that is returned, so the upper and lower parameter arrays are different, a bit like Curry.
The second is the context, where the context changes are difficult to understand. The bind function is mainly used to bind the context.
fToBind = this Here is the object's context, followed by the apply method below to allow the object to be bound to use the context
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
Here, fNOP is used as an intermediary to fBound, ensuring that fBound is executed in the context when it is defined. originally
bound.prototype = self.prototype can integrate the original attributes, but in this way, both object attributes point to the same place, modifying bound.prototype will cause self.prototype to also change, which is not our original intention. Therefore, the transition through an empty function nop can effectively prevent this situation from happening.
The above article about the simple implementation of bind function in native js is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.