The meaning of using the Apply function or the call function:
In the face of object programming, when a object calls other objects instead of the A object method, all of the this references in the method point to the object in which the method resides, not the context of the current code, which is a object.
To maintain the original point of this (that is, the A object), you need to use the Apply or call function.
The difference between apply () and call ():
Apply and call, their role is to bind the function to another object to run
The prototypes were
Function.prototype.apply (Thisarg,argarray);
Function.prototype.call (Thisarg,[arg1],[arg2 ...]);
As you can see, the first parameter is named Thisarg, which means that the this pointer inside all functions is assigned a value of Thisarg, allowing another object instance to pass into the function.
If the Thisobj parameter is not provided, then the Global object is used as the thisobj.
The difference is that the second argument, the Apply () function passes in the numeric value as an array, and the call () function passes directly to multiple values in a free form.
Example:
function accomodation () {
This.isalarmed=false;
}
var alarmsystem={
Arm:function (message) {
This.isalarmed=true;
alert (message);
},
Disarm:function (message) {
This.isalarmed=false;
alert (message);
}
};
var myhouse = new accomodation ();
AlarmSystem.arm.call (Myhouse, "Alarm activated");
alert (myhouse.isalarmed); True the this value in the arm () function points to the Myhouse object through call (), which changes the properties of the Myhouse object
AlarmSystem.disarm.apply (myhouse,["Alarm activated"]);
alert (myhouse.isalarmed); The this value in the flase arm () function points to the Myhouse object through call (), which changes the properties of the Myhouse object
Call () function, apply () function difference and meaning