Use the bind method in JavaScript to refer to it correctly

  • 2020-06-07 04:02:17
  • OfStack

In JavaScript, methods often involve context, namely this, and therefore cannot be referred to directly. For example, instead of writing verbatim console, use log("info... (Without thinking, the following sentences come to mind:


 var log = console.log;
 log("info ... ");

Unfortunately, operation error: 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; We use the log variable to point to the console.log method and then call the log method directly. At this time, the this of the log method points to the window object.

At this point, we can use the bind method to solve this problem. The bind method allows you to manually pass in 1 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...");

So you don't get an error.

However, the bind approach does not support ie 8 or any of the lower versions of the browser, we can implement one of our own, very simple.


 Function.prototype.bind = Function.prototype.bind || function(context){
   var _this = this;
   
   return function(){
     _this.apply(context, arguments);
   };
 };

The core is achieved by the apply method, a classic application of closures. _this points to the current method, context to the context of the current method, both accessed through closures.

This is the end of this article, I hope you enjoy it.


Related articles: