关于call和apply用法

他们都是用来调用其他对象的方法(下例A调用B),实现继承,区别是:call后跟一个个的元素,apply后跟数组。如下:
B.call(A, args1,args2)
B.apply(A, arguments)
另外call和apply还会改变this的指向,在浏览器中this的值是全局对象window。

var aa = '张三'
function a(){
    return this.aa;
}
var obj = {aa:'李四'};
console.log(a());//张三
console.log(a.call(obj));//李四。this不再是window,而是改成obj

ps:但是在ES6 箭头函数里面,由于this在箭头函数中已经按照词法作用域绑定了,所以,用call()或者apply()调用箭头函数时,无法对this进行绑定,即传入的第一个参数被忽略:

var aa = '张三'
a = () => this.aa;
var obj = {aa:'李四'};
console.log(a());//张三
console.log(a.call(obj));//张三。这时候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:不确定几个参数或者参数较多的时候,一般传对象

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"
}*/

多重继承

// 爬行类
function Paxing(leg){
    this.showLeg = function(){
        console.log(leg)
    }
}
// 有毛类
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);这里不能直接用数组,因为Fair的参数和Cat的参数 不一致
}

var cat = new Cat(4,'灰色');
cat.showLeg();//4
cat.showColor();//灰色

你可能感兴趣的:(关于call和apply用法)