The Call/apply/bind in JS

Source: Internet
Author: User

<script>        var obj = {            A:1        }            var a = 2;                 function Test (a)        {            alert (a);            Alert (this. a);        }         </script>

1.test (3);

Results: "3", "2";

Explanation: Argument 3 is passed to parameter a, and parameter a inside the function overrides global variable A, so the first is 3, and this in the function is the window object, so THIS.A is 2

2.test.call (thisobject,param1,param2 ...);

Thisobject: Change the point of this in the test function;

Param: Pass a parameter to the test function as a string

  Test.call (NULL);

Results: "Undefined", "2";

Explanation: When test (a) is executed, no arguments are passed, a is undefined, because the pass thisobject is null, when the test function is executed, the browser points to the Window object when the THISOBEJCT is not pointed, so the second popup is 2. The same test.call (undefined), the result ibid.

3.test.call (null,3);

Results: "3", "2";

4.test.call (obj);

Results: "Undefined", "1";

5.test.call (obj,3);

Results: "3", "1";

6.test.apply (Thisobject,[param1,param2 .....));

In addition to passing parameters to the function in the form of an array, the other and call (Thisobject,param1,param2 ...);

7.test.bind (Thisobject,param1,param2 ...)

Thisobject: Change this to point to

Param: Parameters

This method returns the function object that this change points to, and gets the arguments

var ss = Test.bind (NULL);

SS ();

Result: "Undefined", "2"

var ss = Test.bind (obj);

SS ();

Results: "Undefined", "1";

var ss = Test.bind (obj,3);

SS ();

Results: "3", "2";

When a function has more than one parameter:

function Test (a,b,c) {    alert (a+ ":" +b+ ":" +c);}         var ss = Test.bind (obj,3); SS (4,5,6);

The result: 3,4,5 is not 4,5,6, because in Bind, the 3 is assigned to a, at the SS (4,5,6), 6 is not assigned to C;

The value saved in arguments is 3,4,5,6;

The Call/apply/bind in JS

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.