I. Definition of methods
1. Call ()
Syntax: Call (Thisobj, Object)
Definition: Invokes one 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 object context of a function from the initial context to a new object specified by Thisobj.
If the Thisobj parameter is not provided, then the Global object is used as the thisobj.
2. 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.
Second, common examples
1. Function Add (A, b) {
alert (A+B);
}
function Sub (A, b) {
Alert (A-B);
}
Add.call (sub,3,1); //4
2. var func=new function () {
This.a= "Func"
}
var myfunc=function (x) {
var a= "MyFunc";
alert (THIS.A);
alert (x);
}
Myfunc.call (func, "Var"); //func var starts this point to MyFunc, with the call () method, this points to the Func
3,<input type= "text" id= "MyText" value= "input text" >
function Obj () {
This.value= "Object! ";
}
var value= "global variable";
function Fun1 () {
alert (this.value);
}
Window. Fun1 (); the//global variable is equivalent to FUN1 (); This points to the window
Fun1.call (window); //global Variable
Fun1.call (document.getElementById (' MyText ')); //input Text
Fun1.call (New OBJ ()); //Object!
4, Function Animal () {
THIS.name = "Animal";
This.showname = function () {
alert (this.name);
}
}
function Cat () {
THIS.name = "Cat";
}
var animal = new animal ();
var cat = new Cat ();
//using the call or Apply method, the ShowName () method originally belonging to the animal object is given to the object cat.
The input result is "Cat"
Animal.showName.call (Cat, ",");
Animal.showName.apply (cat,[]);
The call () and apply () methods in JS