call() apply() bind() 的区别

call() apply() bind() 都是改变this指向

call() 执行函数 函数中的this指向第一个参数,其他参数一一传递

apply() 执行函数 函数中的this指向第一个参数,其他参数以数组的形式传递

bind() 返回一个新函数,新函数中的this指向给定的参数

下面是自己总结的call() apply() bind() 的源码

MyCall: function MyCall(){
            var  taregt = arguments[0] || window;
            // 1. 保留参数
            var args = Array.from(arguments).slice(1);
            // 2. 执行函数 this 并且参数进行传递
            // 执行函数时 改变函数中this的指向 并且传递参数给函数
            // 2.1 在改变this指向为指定对象 target上添加一个属性 值为最终调用的函数
            taregt.fn = this;
            taregt.fn(...args);
        }
Function.prototype.apply = function (context, arr) {
    var context = Object(context) || window;
    context.fn = this;

    var result;
    if (!arr) {
        result = context.fn();
    }
    else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')')
    }

    delete context.fn
    return result;
}
MyBind:function myBind(){
        // 1. this改变指向 
        var target = arguments[0] || window;
        // 2. 保留调用bind时 传递的函数中的实参
        // 截取arguments中从下标1开始往后所有的参数
        var args = Array.from(arguments).slice(1);
        // 3. 保留myBind中的this指向  demo
        var self = this;
        return function(){
            // fn1被调用时  其实调用的是demo  demo指向
            // 改变demo的this指向  指向target 并且将参数进行传递
            self. apply(target,args);
        }
    },

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值