How to use bind to specify receiver _ javascript in javascript

Source: Internet
Author: User
This article describes how to use bind to specify the receiver in javascript. For more information, see The Code is as follows:


Var json = {
JArray: [],
JPush: function (c ){
This. jArray. push (c );
}
}
Var examp = ["123 ","~ "," 456 "];


Use the forEach loop examp given by ES5 and add them to jArray in json;

The Code is as follows:


Examp. forEach (json. jPush );


At this time, an error is reported:


The cause of this error is that this in the json. jPush method does not point to the json object, but to the window. The solution to this problem is to find the correct person for this.
Fortunately, forEach () provides a parameter specifically used to specify the object. view the code.

The Code is as follows:


Examp. forEach (json. jPush, json );
Alert (json. jArray); // The result is normal. Yes, 123 ~ 456


There is another method:

The Code is as follows:


Examp. forEach (function (c ){
Json. jPush (c );
});
Alert (json. jArray); // 123 ~ 456


Bind binding can also be used.

The Code is as follows:


Examp. forEach (json. jPush. bind (json ));
Alert (json. jArray );


Bind creates a new function instead of modifying a function. the behavior of the new function is the same as that of the original function. However, the receiver of the new function is the given object, while the receiver of the original function remains unchanged.
This means that the bind method is safe to use, because when a function or method is shared, you don't have to worry that the sharing method will not be modified.
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.