JavaScript中call和apply方法

JavaScript中call和apply方法

call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

call()方法与apply()方法类似只是call()传入参数列表,而apply()传入数组

这么说很迷,举个例子

function Animal() {
    this.name = 'Animal';
    this.age = 0;
    this.showName = function (age) {
        console.log(this.name + ' ' + age);
    }
}

function Cat() {
    this.name = 'Cat';
}

let animal = new Animal();
let cat = new Cat();

cat.showName();
//TypeError: cat.showName is not a function

现在我们想让cat能使用animal中的showName方法那就使用call

animal.showName.call(cat);
//注意showName不需要加()

//结果
//Cat undefined

因为Cat没有showName方法,所以我们使用call方法让cat去调用了animal中的showName方法,但是因为showName方法需要参数,我们没有传参数进去,所以this.ageundefineed,传参也很简单

animal.showName.call(cat, 19);
//Cat 19

既然可以让一个对象使用另一个对象的方法,那么就可以用它来实现继承

function Animal(name, age) {
    this.name = name;
    this.age = age;
    this.showName = function () {
        console.log(this.name + ' ' + this.age);
    }
}

function Cat(name, age) {
    Animal.call(this, name, age);
}


let cat = new Cat('Blcak Cat', 19);

cat.showName();
//Black Cat 19

版权声明:本文为SOUIC原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。