In JavaScript, methods often involve context, which is this, so they often cannot be quoted directly. Take the most common console.log("info...") as an example. Avoid writing lengthy consoles and directly use log( "info..."), you will automatically think of the following syntax:
var log = console.log; log("info…");
Sorry, the error occurred when running: 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 call the log method directly. At this time This of the log method points to the window object. If the context is inconsistent, of course an error will be reported.
At this point we can use the bind method to solve this problem. The bind method allows you to manually pass in a this as the context of the current method, and then return the method holding the context, for example:
var log = console.log.bind(console); log("info...");
This way there will be no errors.
However, the bind method does not support IE 8 and lower browsers. We can implement one ourselves, it 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, a classic application of closure. _this points to the current method, and context points to the context of the current method, both of which are accessed through closures.
The above is the entire content of this article, I hope you all like it.