<! 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