First, call
Call (Thisobj,arg1,arg2,arg ...)
Definition: Invokes the method of an object, replacing the current object with another object.
Description: The call method can be used to invoke a method in place of another object.
The call method can change the context of a function object to a new object specified by Thisobj.
There are several cases where the value of Thisobj is as follows:
(1) When not transmitted, or null,undefined, this point in the function points to the Window object;
(2) A function name that passes another function, and this in the function points to the reference to the function;
(3) When passing the underlying type data, this in the function points to its corresponding wrapper object;
(4) When passing an object, this object is pointed to in the function.
Example 1--> calls the Max method of math to implement a sequence of numbers:
Example 2--> calling fn1 method to print information in FN2
Example 3--> implementing Inheritance:
Fn1.call (this) means that the Fn1 object is substituted for the This object, and FN2 can invoke all the properties and methods of FN1.
Second, apply
Syntax: Apply (Thisobj,argarray)
Definition: A method of applying an object that replaces the current object with another object.
Description: If Argarray is not a valid array or is not a arguments object, it will result in a TypeError.
If none of the Argarray and Thisobj parameters are provided, then the Global object is used as a thisobj and cannot be passed any parameters.
The function is different from the call, and the method of transmitting the parameter. For example, refer to call, here a little.
third, bind
The Bind method creates a new function, which is described on the MDN:
The bind () method creates a new function (called a binding function), and when the function is called, its this keyword is set to the supplied value, and a given parameter sequence is provided when the new function is called.
Function.bind (THISOBJ,ARG1,ARG2,ARG3): Parameter thisobj means: When the bound function is called, this is pointed to for that parameter. When a binding function is called with the new operator, the parameter thisobj is invalid. Parameter Arg1,arg2,... Represents: When a binding function is called, these parameters are passed to the bound method before the argument is placed.
This.name= "Jack"
var demo={
Name: "Lily",
Getname:function () {return this.name}
}
var name1= demo.getname;
Console.log (name1 ())
var name2 = Name1.bind (Demo)
Console.log (Name2 ())
Results:
Jack
Lily
Console.log (name1 ())//Output jack, here's this point to the global object
Console.log (Name2 ())//Output Lily, here the This points to the name object
To preset an initial value for a function:
var add = function (x, y) {return x+y}
var Add_curr = Add.bind (null,2)
Add_curr (3)
Results: 5
The use of Call,apply,bind in JavaScript