This article focuses on the implementation of the bind () method. before we begin to discuss the implementation of bind (), let's take a look at the use of the bind () method. if you need it, refer to it. In JavaScript, the method often involves context, that is, this, so it is often not directly referenced, take the most common console. log ("info... ") To avoid lengthy console writing, directly use log (" info... ") Instead, you will think of the following syntax without thinking about it:
var log = console.log; log("info…");
Unfortunately, the following error occurs: TypeError: Illegal invocation.
Why? For console. log ("info... "), The log method is called on the console object, so this in the log method points to the console object, and we use the log variable to point to the console. log method, and then directly call the log method. this of the log method points to the window object, and the context is inconsistent. of course, an error is returned.
In this case, we can use the bind method to solve this problem. The bind method allows you to manually input this as the context of the current method, and then return the method that holds the context, for example:
var log = console.log.bind(console); log("info...");
In this way, no error is reported.
However, the bind method does not support ie 8 or earlier browsers. we can implement one by ourselves, which is very simple.
Function.prototype.bind = Function.prototype.bind || function(context){ var _this = this; return function(){ _this.apply(context, arguments); }; };
The core is implemented through the apply method, which is a classic application of closures. _ This points to the current method, and context points to the context of the current method, both of which are accessed through the closure.
The above is all the content of this article. I hope you will like it.