JavaScript function calls are grouped into 4-mode:
1. Method invocation Pattern: Object contains method properties, Obj.methodname () or Obj[methodname] ().
2. Function call Mode: MethodName ().
3. Constructor invocation pattern: New MethodName ().
4. Apply and call invocation mode: Obja.apply (objb,args[]) or Obja.call (Objb,arg1,arg2 ...).
When a function is called, it receives the this and arguments in addition to the form arguments received. Where this is the function object context, arguments is the actual argument.
Apply and call implement the same function, which is to toggle the context of the function object (this refers to the reference), except that the formal parameters are different. Apply is a arguments or array, and call is a comma-separated number of individual form parameters.
function Add (c)
{
alert (this.a+this.b+c);
}
var test={a:1,b:2}
Add.call (test,3);
In the implementation of Add.call (test,3); Add and test are all under window, and this point to window. Add.call (test,3); When executed, enter the Add method body when this is switched from window to test, at which point This.a=test.a,this.b=test.b,c is passed the value of the formal parameter, that is, the result of alert () is 1+2+3=6. Apply is also the same function.
Extend and inherit through apply and call:
function Animal (name) {
this.name = name;
This.showname = function () {
alert (this.name);
}
}
function Cat (name) {
Animal.call (this, name);
}
var cat = new Cat ("Black Cat"), when executing, the cat function body's This is switched by window to cat{},
///animal function body's this.name passes the form parameter to namely Black Cat, the final cat
//The result is cat=cat{name: "Black Cat", showname:function () {alert (this.name);},
cat.showname ();// This is toggled by window to
//cat{name: "Black Cat", showname:function () {alert (this.name);} this.name
// For This.name=cat.name, so black Cat.