In JS, each function contains two non-inherited methods, apply () and call (), allowing us to invoke the function in a specific scope.
Let's talk about the similarities:
take call first as an example:
Window.color = "Red"; var o = {color: "Blue"}; function Saycolor () { alert (this. color); Console.log (this); } Saycolor (); Red Saycolor.call (this); Red saycolor.call (window); Red saycolor.call (o); Blue
In the above code, four Saycokor () functions were called, the first, the direct call, and the second with the current this as the object invocation (Saycolor (this)), and the direct call to window as an object, refers to the current Window object ( Can be understood as a global object), returns the Color property of window, and on the fourth invocation, the object o passes past, at which point the color property called by the Saycolor method is the Color property of Object O.
and for Apply ():
The implementation is almost the same as call, and the difference is that when a function needs to pass in a parameter, apply () can use the parameter array, and call () only passes the argument one at a time.
Cases:
Apply (this, [Num1, num2]);
Call (this, NUM1, num2);
The specific use of the environment is also dependent on the circumstances.
Say something about them: there is no need to have any coupling between the object and the method , in general, in addition to the Window object, it is very difficult for us to directly use the object and the object does not have a half-wool relationship or in the same scope of the method.
By the way, add the statements of these two functions that you have recently used:
How to get the maximum minimum value in an array:
var max2 = Math.max.apply (math,values);
The Math object is used as the first parameter of apply () to set the this value correctly.
Knowledge Point Supplement: A Window object, a Web browser that generally says global variables are implemented as part of the Window object's properties. Therefore, all variables and functions declared under the global scope are referred to as properties of the Window object .