In JavaScript oop, we often define this:
function Cat () {
}
cat.prototype={
Food: "Fish",
Say:function () {
Alert ("I Love" +this.food);
}
}
var blackcat = new Cat;
Blackcat.say ();
But if we have an object Whitedog = {food: "Bone"}, we do not want to redefine it say method, then we can use call or Apply with Blackcat say method: BlackCat.say.call (Whitedog );
So, you can see that call and apply are meant to change this dynamically, and when an object does not have a method, but the others, we can use call or apply to manipulate other objects.
The DOM node chosen by document.getElementsByTagName is a type of array that is similar to array. It cannot apply methods such as Push,pop under the array. We can do this by:
var domnodes = Array.prototype.slice.call (document.getElementsByTagName ("*"));
This allows the domnodes to apply all the methods under the array.
1.call ()
Syntax: Obj1.call (obj2[,param1,param2,...])
Definition: Use Obj2 object instead of Obj1, call obj1 method. The obj1 will be applied to the OBJ2.
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 Obj2. If the OBJ2 parameter is not provided, then the Global object is used as the obj2.
2.apply ()
Syntax: Obj1.call (Obj2[,arrarg])
Definition: Use Obj2 object instead of Obj1, call obj1 method. The obj1 will be applied to the OBJ2.
Note: Call () is the same as apply (), but call () can receive parameters of any type, and apply () can only receive array parameters.
3. Basic usage
[JavaScript]View PlainCopy
- function Add (A, b) {
- return a+b;
- }
- function sub (c,d) {
- return c-d;
- }
- function result () {
- this.addvalue = null;
- this.subvalue = null;
- this.showresult=function () {
- Alert (this.addvalue);
- Alert (this.subvalue);
- }
- }
- var r = new result ();
- R.addvalue = Add.call (sub,4,2); //6, apply the Add method to the sub, which is the pointer to the sub that points to the Add method
- R.subvalue = Sub.call (add,4,2); //2, replacing the sub object with the Add object, and invoking the method of the Sub object
- R.showresult (); //In JS The function is also a functions object, the function name is the object reference
4. Inheritance Features
[JavaScript]View PlainCopy
- function Add (A, b) {
- return a+b;
- }
- function sub (c,d) {
- return c-d;
- }
- function result () {
- this.addvalue = null;
- this.subvalue = null;
- this.showresult=function () {
- Alert (this.addvalue);
- Alert (this.subvalue);
- }
- }
- var r = new result ();
- R.addvalue = Add.call (r,4,2); //6,r inherit all the attributes of the Add function
- R.subvalue = Sub.call (r,4,2); //2,r all features of the integrated sub function
- R.showresult ();
The call apply in JS