call和apply

call/apply

作用,改变 this 指向。
区别,后面传的参数形式不同

例如:

	function Person(name, age) {
        this.name  = name;
        this.age = age;
    }
    var person = new Person('deng',100);
    var obj = {


    }
    Person.call(obj, 'chen', 180)

在这里插入图片描述
如果 Person.call( obj );
里面的 call 让 person 所有的 this 都变成 obj。
不 new 的话,this 默认指向 window。call 的使用必须要 new。
call 的第一位参数用于改变 this 指向,第二位实参(对应第一个形参)及以后的参数都当做正常的实参,传到形参里面去
借用别人的方法,实现自己的功能。

例如:

 	function Person(name, age, sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    function Student(name, age, sex, tel, grade) {
        Person.call(this, name, age, sex);
        this.tel = tel;
        this.grade = grade;
    }
    var student = new Student('sunny', 123, 'male', 139, 2020);

在这里插入图片描述
call 改变 this 指向,借用别人的函数,实现自己的功能。
只能在你的需求完全涵盖别人的时候才能使用
Person.call(this, name, age, sex);里面的 this 现在是 new 了以后的 var this={}
利用 Person 方法,实现了 Student 自己的封装
例如:

 function Wheel(wheelSize, style) {
        this.wheelSize = wheelSize;
        this.style = style;
    }
    function Sit(c, sitColor) {
        this.c = c;
        this.sitColor = sitColor;
    }
    function Model(height, width, len) {
        this.height = height;
        this.width = width;
        this.len = len;
    }
    function Car(wheelSize, style, c, sitColor, height, width, len) {
        Wheel.call(this, wheelSize, style);
        Sit.call(this,c, sitColor);
        Model.call(this, height, width, len);
    }
    var car = new Car(100, '花里胡哨', '真皮', 'red', 1900, 1800, 4900);

在这里插入图片描述
apply 也是改变 this 指向的,只是传参列表不同,第一位也是改变 this 指向的人,第
二位。apply 只能传一个实参,而且必须传数组 argunments
call 需要把实参按照形参的个数传进去

如果用apply,例如:

	function Wheel(wheelSize, style) {
        this.wheelSize = wheelSize;
        this.style = style;
    }
    function Sit(c, sitColor) {
        this.c = c;
        this.sitColor = sitColor;
    }
    function Model(height, width, len) {
        this.height = height;
        this.width = width;
        this.len = len;
    }
    function Car(wheelSize, style, c, sitColor, height, width, len) {
        Wheel.apply(this, [wheelSize, style]);
        Sit.apply(this, [c, sitColor]);
        Model.apply(this, [height, width, len]);
    }
    var car = new Car(100, '花里胡哨', '真皮', 'red', 1900, 1800, 4900);

在这里插入图片描述
结果和call一样的

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值