Home > Web Front-end > JS Tutorial > Correctly referencing the application of bind method in JavaScript_javascript tips

Correctly referencing the application of bind method in JavaScript_javascript tips

WBOY
Release: 2016-05-16 15:59:55
Original
1319 people have browsed it

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…");
Copy after login

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...");

Copy after login

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);
   };
 };

Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template