And the difference between call and apply usage

ECAMScript3 Function prototypes to define two methods, Function.prototype.call and Function.prototype.apply.

Differ only in the form of parameters passed.

var FUNC = function (A, B, C) { 
      the console.log ([A, B, C]); 
} 
func.apply ( null , [1,2,3]); // Output [1,2,3 ] 
func.call ( null , 1,2,3); // output [2,3]

usage:

1, change this point. call and apply the most common use is to change this point to the internal functions.

var name="window"
var obj1={
    name:"obj1"
};
var ob2={
    name:"obj2"
};
var getName=function(){
    console.log(this.name);
}
getName();//window
getName.call(obj1);//obj1   this指向obj1
getName.call(obj2);//obj2   this指向obj2

2, a method borrowed from other objects

var A={
    name:"小王",
    getName:function(){
        console.log(this.name);
    }
};
var B={
    name:"丽丽"
};

A.getName.call(B);

 

Guess you like

Origin www.cnblogs.com/liangtao999/p/11688976.html