Usage of apply and call

Source: Internet
Author: User

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>04-apply and Call Methods </title>
<script>

Apply and Call methods
Function: You can set the specific caller of the function to modify the scope of the function
First argument: refers to the caller of the function
var color = ' green ';
var getColor = function () {
var color = ' Blue ';
Console.log (color);
Console.log (This.color);
}
GetColor ();
Window.getcolor ();
Getcolor.apply (this);
Getcolor.call (this);


var obj1 = {
Color: ' Yellow '
};
Equivalent to Obj1 to invoke GetColor
Getcolor.apply (OBJ1);
Getcolor.call (OBJ1);

var obj2 = {
Color: ' Red ',
}
Assign the GetColor function to the Obj2 object's property ABC
If there is an ABC attribute in OBJ2, then the following statement modifies the ABC property, and if there is no ABC attribute in OBJ2, add an ABC attribute to OBJ2
OBJ2.ABC = GetColor;
Call the ABC property of OBJ2
OBJ2.ABC ();


function sum (num1,num2) {
return NUM1 + num2;
}

var = sum (RESULT1);
Console.log (RESULT1);
The Apply method passes the arguments of the calling function, using an array, or an array of classes
var result2 = sum.apply (this,[1,2]);
Console.log (RESULT2);

function Callsum (NUM3,NUM4) {
Return sum.apply (this,arguments);
}
var result3 = callsum (2,3);
Console.log (RESULT3);


The call method passes the arguments of the calling function, which is to pass in the argument to one
var result4 = Sum.call (this,5,8);
Console.log (RESULT4);

Summary: Apply and Call methods:
The first parameter is similar, followed by a different argument.

</script>

<body>

</body>

Usage of apply and call

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.