Use and apply the difference between the call and

apply :

Function.apply (obj, args) accepts two parameters:

obj: Function of this change point to point obj;

args: an array of parameters passed to the function;

call:

Function.call(obj, param1, param2, param3...)

obj: Function of this change point to point obj;

args: an array of parameters passed to the function;

Example:

function add(c, d) {
    return this.a + this.b + c + d;
}
var strObj = {A: 'today', b: 'weather' };
console.log (add.apply (strObj, [ 'true', 'good'])); // Nice weather 
console.log (add.call (strObj, 'true', 'good'));     // Beautiful day

 

apply and call the difference between:

  • Different parameters passed in the form of:

    Apply only two parameters, the first parameter is the object of this point, the second parameter is an array of parameters consisting incoming Funtion;

    There is a call and the above parameters, the first parameter is the object pointed to this, the back of the parameters are passed in Function parameters, there are two Function is passed two parameters, there are three that passed the three, there are a few several months pass;

  • Use different scenarios:

    If the formal parameter is an array type, and, when invoked, a consistent order of the parameters (the position where chaos for parameters does not occur), such as: parent function is Person (name, age) Functions Student (name, age, grade), you can use apply;

    If the parameter is inconsistent sequence, such as: parent function Person (name, age) Functions Student (age, name, grade), Call can be used, a position parameter corresponding to the specified value (Student.call (this, name, age, grade) );

apply and may call for inheritance

 

function Class10(){
  this.showSub = function(a,b){
        alert(a - b);
    }   
}
 
function Class11(){
  this.showAdd = function(a,b){
        alert(a + b);
    }  
}
 
function Class12(){
  Class10.apply(this);
  Class11.apply(this);   
  // Class10.call(this);
  //Class11.call(this);  
}
 
var c2 = new Class12();
c2.showSub(3,1);    //2
c2.showAdd(3,1);    //4

 

Guess you like

Origin www.cnblogs.com/zhizhi0810/p/11921408.html