他們都是用來(lái)調(diào)用其他對(duì)象的方法(下例A調(diào)用B),實(shí)現(xiàn)繼承,區(qū)別是:call后跟一個(gè)個(gè)的元素,apply后跟數(shù)組。如下:
B.call(A, args1,args2)
B.apply(A, arguments)
另外call和apply還會(huì)改變this的指向,在瀏覽器中this的值是全局對(duì)象window。
var aa = '張三'
function a(){
return this.aa;
}
var obj = {aa:'李四'};
console.log(a());//張三
console.log(a.call(obj));//李四。this不再是window,而是改成obj
ps:但是在ES6 箭頭函數(shù)里面,由于this在箭頭函數(shù)中已經(jīng)按照詞法作用域綁定了,所以,用call()或者apply()調(diào)用箭頭函數(shù)時(shí),無(wú)法對(duì)this進(jìn)行綁定,即傳入的第一個(gè)參數(shù)被忽略:
var aa = '張三'
a = () => this.aa;
var obj = {aa:'李四'};
console.log(a());//張三
console.log(a.call(obj));//張三。這時(shí)候this還是window
繼承用法
function Animal(name,age){
this.name = name;
this.age = age;
this.showName = function(){
console.log(this.name);
}
this.showAge = function(){
console.log(this.age);
}
}
function Dog(name,age){
// Animal.apply(this,[name,age]);
Animal.apply(this,arguments);
}
function Pig(name,age){
Animal.call(this,name,age)
}
var dog = new Dog('zhangsan',5);
var pig = new Pig('lisi',2);
dog.showName();//zhangsan
dog.showAge();//5
pig.showName();//lisi
pig.showAge();//2
ps:不確定幾個(gè)參數(shù)或者參數(shù)較多的時(shí)候,一般傳對(duì)象
function Person(obj){
this.age = 18;
this.name = obj.name;
this.sex = obj.sex;
}
function Student(obj){
Person.call(this,obj)
}
var wangwu = new Student({name:'王五','sex':'man'});
console.log(wangwu);
/*{
age:18,
name:"王五",
sex:"man"
}*/
多重繼承
// 爬行類(lèi)
function Paxing(leg){
this.showLeg = function(){
console.log(leg)
}
}
// 有毛類(lèi)
function Fair(color){
this.showColor = function(){
console.log(color)
}
}
function Cat(leg,color){
Paxing.call(this,leg);
Fair.apply(this,[color]);
// Fair.apply(this,arguments);這里不能直接用數(shù)組,因?yàn)镕air的參數(shù)和Cat的參數(shù) 不一致
}
var cat = new Cat(4,'灰色');
cat.showLeg();//4
cat.showColor();//灰色