对于js中apply和call的区别和用法

在学习js继承的时候,apply和call出现的频率很高,心里也只是有个大概的理解,刚好今天有时间,就整理一下。
首先,apply和call是干嘛用的?
他们一般用来改变函数执行时的上下文,再具体一点就是改变函数运行时的this指向
一句话概括:用来重定义 this的!
听起来好像很懵,来看代码:

            function Person(skinColor = 'yellow', gender = 1, age = 1) {
                this.skinColor = skinColor;
                this.gender = gender;
                this.age = age;
                this.eat = function () {
                    console.log('eating!');
                }
            }
            function Bob(ability = ['eat', 'move brick'], profession = 'programmer') {
                this.name = 'Bob';
                this.ability = ability;
                this.profession = profession ;
                Person.call(this, 'white', 0, 22);
            }
            const bob = new Bob();

在这里插入图片描述
在使用了call之后,Bob拥有了Person的属性,这里就是我之前关于继承的文章中所写的构造函数继承。
我们来看这句代码:Person.call(this, ‘white’, 0, 22);

	  function Bob(ability = ['eat', 'move brick'], profession = 'programmer') {
            this.name = 'Bob';
            this.ability = ability;
            this.profession = profession ;
            Person.call(this, 'white', 0, 22);
       }

显然这里的this指的是Bob,而Person.call(this),看起来是不是很像把this(也就是Bob)当做参数传递给Person了。传递到Person之后,执行了Person的初始化代码:
this.skinColor = skinColor;
this.gender = gender;
this.age = age;
但是这里的this其实已经变成了Bob,也就是说通过call,巧妙的把一些初始化给Person的属性,给到了Bob。
apply也是同样的道理。

他们的区别在哪里?
区别其实就一点:传参方式不同
call(this, arg, arg1, arg2,…);
apply(this, [arg, arg1, arg2,…]);
他们的第一个参数都是当前对象,不同的是call传参是一个一个一个的传下去,apply是传递数组,或者arguments对象。
因为call的传参方式是一个一个的,所以call比较适用于参数,和参数数量明确的情况下,apply因为传递的数组则反之。
在其他博客里我看到还有一种说法:call其实是apply的语法糖,所以除非参数数量不明确,否则用call要好一点,因为参数可以按顺序一一对应,代码比较易懂。

一些其他的用法:

1、求数组的最大最小值
var arr = [1, 2, 3,…n];
Math.min.apply(this,arr); this可随便换,但需是一个对象,传null也可以,为null时默认为当前window对象。

2、将arr2的值放入到arr1中
var arr1= [1,2,3],
arr2= [5,6,7,8];
不需要contact,不需要循环push。
直接Array.prototype.push.apply(arr1,arr2);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值