Using _javascript techniques to correctly reference the Bind method in JavaScript

Source: Internet
Author: User

In JavaScript, the method often involves the context, that is, this is so often not directly referenced, take the most common console.log ("info ...") to avoid writing a lengthy console, directly using log ("info ...") instead, Without thinking, you would think of the following syntax:

 var log = Console.log;
 Log ("info ...");

Unfortunately, run the error: Typeerror:illegal invocation.

Why, then? For Console.log ("info ..."), the log method is invoked 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, this time the log method is pointing to the Window object, the context is inconsistent, of course, the error.

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 for the current method, and then returns a method that holds the context, for example:

 var log = Console.log.bind (console);
 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, very simple.

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

The core is implemented by applying method, and the classic closure is applied. _this points to the current method, which points to the context of the current method, both of which are accessed through closures.

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.