Call and apply
Call and apply can be used to redefine the execution environment of the function, that is, the point of this, which is very common for some applications.
Call () methodExample:
Function Changestyle (type, value ){
This. Style [type]=Value;
}
VaROBJ=Document. getelementbyid ('Div1');
Changestyle. Call (OBJ,'Fontsize','20px');
Changestyle ('Fontsize','30px');//Error. In changestyle, This references the window object.
Note that the changestyle. Call () method has three parameters.
The first parameter is used to specify The object to which the function is called. O is specified here. BJ , Which means that the changestyle function will be BJ Therefore, this point in the function body is o BJ Object. The second and third parameters correspond to the type and value parameters in the changestyle function. Final The result we see is the DOM element O. BJ The font of is 20 PX.
Apply () methodExample:
VaR OBJ = Document. getelementbyid ( ' Div1 ' );
Changestyle. Apply (OBJ ,['Fontsize','20px']);
Changestyle ('Fontsize','30px');//Error. In changestyle, This references the window object.
The usage of "Apply" is roughly the same as that of "call". There is only one difference. "Apply" only accepts two parameters. The first parameter is the same as "call,The second parameter must beArrayThe elements in the array correspond to the form parameters of the function.
Content from blog