How to correctly reference a method in JavaScript (the application of the Bind method)

Source: Internet
Author: User

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)

Related Article

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.