In JavaScript, the method often involves the context, that is, this, so often can not directly reference, take the most common console.log ("info ..."), avoid writing lengthy console, directly with the log ("info ...") instead, Think of the following syntax without hesitation:
1 var log = console.log; 2 log ("info ...");
Unfortunately, the operation error: Typeerror:illegal invocation.
Why is it? 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, when the log method of this point to the Window object, the context is inconsistent, of course, will be error.
At this point we can solve this problem with the bind method. The Bind method allows you to manually pass in a this, as the context of the current method, and then return the method that holds the context, for example:
1 var log = console.log.bind (console); 2 log ("info ...");
This will not be an error.
However, the Bind method does not support IE 8 and the lower version of the browser, we can fully implement one ourselves, very simple.
1 function (context) {2 var This ; 3 4 return function () {5 _this.apply (context, arguments); 6 }; 7 };
The core is implemented through the Apply method, the closure of the classic application. _this points to the current method, which points to the context of the current method, both of which are accessed through closures.
How to correctly reference a method in JavaScript (the application of the Bind method)