In JavaScript, methods often involve context, that is, this, so they often cannot be directly quoted. Take the most common ("info...") as an example. Avoid writing a lengthy console and use log("info...") instead. Without thinking, you will think of the following syntax:
var log = ; log("info…");
Unfortunately, the operation error was reported: TypeError: Illegal invocation.
Why? For ("info..."), the log method is called on the console object, so this in the log method points to the console object; while we use the log variable to point to the method, and then directly call the log method. At this time, this log method points to the window object, and the context is inconsistent, and of course an error will be reported.
At this time, we can use the bind method to solve this problem. The bind method allows a manual pass in this as the context of the current method and then returns the method holding the context, for example:
var log = (console); log("info...");
This way there will be no error.
However, the bind method does not support ie 8 and lower versions of browsers. We can implement one by ourselves, which is very simple.
= || function(context){ var _this = this; return function(){ _this.apply(context, arguments); }; };
The core is implemented through the apply method and a classic application of closures. _this points to the current method, and context points to the current method's context, both of which are accessed through closures.
The above is the entire content of this article, I hope you like it.