How JavaScript uses bind to specify the recipient

Source: Internet
Author: User
Tags foreach bind json

This article mainly describes how JavaScript uses bind to designate recipients, and the friends you need can refer to the

The code is as follows:

var json = {

Jarray: [],

Jpush:function (c) {

This.jArray.push (c);

}

}

var examp = ["123", "~", "456"];

Use the foreach loops given by ES5 to examp them and add them to the Jarray in JSON;

The code is as follows:

Examp.foreach (Json.jpush);

This time will be an error:

This error is caused because this in the Json.jpush method does not point to the JSON object, but to window. The way to solve this problem is to find the right person for this one.

Fortunately foreach () provides a parameter specifically for the specified object. Look at the code.

The code is as follows:

Examp.foreach (Json.jpush,json);

Alert (Json.jarray)//The result is normal, 123~456.

There is another way:

The code is as follows:

Examp.foreach (function (c) {

Json.jpush (c);

});

alert (json.jarray);//123~456

You can also use bind bind

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 new function behaves the same as the original function, but his receiver is the given object and the receiver of the original function remains unchanged.

This means that the use of the bind method is very safe because a function or method is shared without fear that the shared 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.