Deep understanding of JS Function.prototype.bind () Method _ Basic knowledge

Source: Internet
Author: User
Tags bind time interval

Objective

For functional bindings (function binding) It's probably the least bit of attention when you're using JavaScript, but when you realize that you need a solution to keep this context in another function, what you really need is actually Function.prototype.bind() , It's just that you're probably still not aware of this.

The first time you encounter this problem, you may prefer to set this to a variable so that you can continue referencing it after changing the context.

I. The grammar of BIND

bind()The main function of a method is to bind a function to an object, and the bind() method creates a function in which the value of the This object is bound to the bind() value of the passed-in function.

1.1 Definition

Bind () is defined as follows:

The bind () method creates a new function that is, when called, has it this keyword set to the provided value, with a given s Equence of arguments preceding any provided when the new function is called.

The bind () function creates a new function (called a binding function), and the new function has the same function as the modulated function (the target function of the binding function). The first parameter that the this value is bound to when the target function is invoked bind() cannot be overridden.

1.2 Principle

The following code can be used to simulate bind() the principle:

Function.prototype.bind = function (context) {
 var self = this;///Save original function
 return functions () {//Returns a new function returned
  Self.apply (context, arguments); When the new function is executed, the incoming contextual context is used as this} for the new function

1.3 Grammar

Function.prototype.bind (thisarg[, arg1[, arg2[, ...)]]

Two. The application scenario of BIND

2.1 Implementing Object Inheritance

var A = function (name) {
 this.name = name;
}

var B = function () {
 A.bind (this, arguments);

B.prototype.getname = function () {return
 this.name;
}

var B = new B ("Hello");
Console.log (B.getname ()); "Hello"

2.2 Event Handling

var paint = {
 color: "Red",
 count:0,
 updatecount:function () {
  this.count++;
  Console.log (This.count);
 }
;

Error method for event handler function binding:
document.queryselector (' button ')
 . AddEventListener (' click ', Paint.updatecount); The this point of the Paint.updatecount function becomes the correct method for binding the DOM object

//event handler:
document.queryselector (' button ')
 . AddEventListener (' Click ', Paint.updateCount.bind (paint)); The this point of the Paint.updatecount function becomes paint

2.3 Time interval function

var notify = {
 text: "Hello world! ",
 beforerender:function () {
  alert (this.text);
 },
 render:function () {

  //error method:
  settimeout (this.beforerender, 0); Undefined

  //correct method:
  settimeout (This.beforeRender.bind (this), 0);//"Hello world! "
 }
};

Notify.render ();

2.4 Native method of borrowing array

var a = {};
Array.prototype.push.bind (A, "Hello", "World") ();

Console.log (a); "Hello", "World"

Three. The browser compatibility of the bind () method

Four. bind () Compatibility notation

if (! Function.prototype.bind) {
 Function.prototype.bind = function () {
  var self = This,//Save original function Context
   = [].shi Ft.call (arguments),///need to bind the this context
   args = [].slice.call (arguments);////////////////////////
  When a new function is returned//
   executes the new function, the incoming contextual context is used as this
   ///And the new function is combined two times, as the parameter of the new function return
   self.apply. Concat.call (args, [].slice.call (arguments)));}}

Five. The difference between bind and Call/apply methods

Common:

Can change the context of function execution;

Different points:

Bind: Functions are not executed immediately, generally used in asynchronous invocations and events; Call/apply: Execute functions immediately.

Summarize

Well, the above is the entire content of this article, I hope the content of this article for everyone to learn or use JavaScript can have some help, if you have questions you can message exchange.

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.