call与applay 整理

基本用法

    function Cat() {}

    Cat.prototype = {
        food: "fish",
        say: function () {
            console.log("I love " + this.food);
        }
    };

    var blackCat = new Cat();
    //另一种写法
    // var blackCat = {
    //     food: "fish",
    //     say: function () {
    //         console.log("I love " + this.food);
    //     }
    // };
    blackCat.say();
    // I love fish
    var dog = {
        food: 'bone'
    };

    blackCat.say.call(dog);
    //  I love bone

call 和 apply 是为了动态改变this而出现的。当一个object没有某个方法,但是其他的有,就可以通过call 或者 apply 来调用其他对象的方法。

语法:第一个参数表示 要改变的this对象,后面的参数为方法中的参数。
call 和apply 的使用区别:call 为连续传参,apply为组合传参, 把需要的参数组合成[xxx,xxx] 格式。

Tips:如果call或apply的第一参数是null的话, this指向window。

此处借鉴他人的一个速记口诀:

猫吃鱼,狗吃肉,奥特曼打小怪兽。
有天狗想吃鱼了
猫.吃鱼.call(狗,鱼)
狗就吃到鱼了
猫成精了,想打怪兽
奥特曼.打小怪兽.call(猫,小怪兽)
// 奥特曼.打小怪兽.apply(猫,[小怪兽])

通过call 和apply 实现对象继承

JavaScript中没有类的概念,继承描述对象之间的关系,继承关键在于子类获取父类的成员及方法的方式

var Parent= function(){
    this.name = 'xiaoming';
    this.age = 22;
}

var child = {};
console.log(child)  //{}
Parent.call(child);
console.log(child);  //{name: "xiaoming", age: 22}

换种方式

    //call方法实现继承
    function Parent(name) {
        this.name = name;
        this.sayHello = function () {
            console.log(name);
        }
    }

    function Child(name, age) {
        //子类的this传给父类
        Parent.call(this, name);
        this.age = age;
        this.sayWorld = function () {
            console.log(age);
        }
    }

    var parent = new Parent("张三");
    var child = new Child("李四", 20);

    //Child {name: "李四", sayHello: ƒ, age: 20, sayWorld: ƒ}
    parent.sayHello();
    child.sayHello();
    child.sayWorld();

Parent.call(this, name);
执行这一步的时候,就会把Parent 的sayHello方法带给Child。

… 后期补充

猜你喜欢

转载自blog.csdn.net/shi_6_tians/article/details/84645408
今日推荐