JS中apply、call、bind的区别

1)apply:两个参数,第一个是this指向,第二个是函数接受的参数,以数组形式传入
2)call:两个参数,第一个是this指向,第二个是参数列表
3)bind:两个参数,第一个是this指向,第二个是参数列表,改变this指向不会立即执行,返回一个永久改变this指向的函数

如果this指向为undefined,那么实际上是指向windows

        function fun(...arguments) {
            console.log(this);
            console.log(...arguments);
        }
        var person = {
            name: 'jack'
        }
        console.log('--------------------');
        fun.apply(person, [1, 2, 3, 4, 5])
        fun(1, 2, 3, 4, 5)
        fun.apply(null, [1, 2])
        fun.apply(undefined, [1, 2])
        console.log('--------------------');
        fun.call(person, 1, 2, 3, 4, 5)
        fun(1, 2, 3, 4, 5)
        fun.call(null, 1, 2)
        fun.call(undefined, 1, 2)
        console.log('--------------------');
        var bindFun=fun.bind(person, 1, 2, 3, 4, 5)
        bindFun()
        var bindFun1=fun.bind(undefined,1,2)
        bindFun1()

在这里插入图片描述

this指向的情况“
1)以函数形式调用,this永远都是window
2)以方法的形式调用,this是调用方法的对象
3)以构造函数形式调用(new),this是新创建的那个对象
4)使用call和apply调用时,this是指定的那个对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值