this绑定——call、apply、bind

先说说,this 就相当于我们人的父母,谁生下我,谁就是我的父母。对应到我们的函数中的this就是谁调用了我,我就指向谁。但是!我们人不仅有亲生父母,也可能因为家庭的缘故会有养父养母。在我们函数中也是一样的,我可能不想让我的this绑定到我的调用者身上,所以这时我们就需要其他的一些处理手段,也就是本文的主角call、apply、bind

基本使用方法:

      var obj = { name: "张三" };
      function fn(a, b) {
        console.log(a, b);
        console.log(this.name);
      }
      fn.call(obj, 'call', 1);
      fn.apply(obj, ['apply', 1]);

      fn.bind(obj)('bind', 1);
      fn.bind(obj, 'bind')(2);

在这里插入图片描述

手写试试?

1、call

      Function.prototype.call_ = function (context, ...args) {
        context = (context === null || context === undefined) ? window : context;
        context.fn = this;
        const result = context.fn(...args);
        delete context.fn;
        return result;
      };

2、apply

      Function.prototype.apply_ = function (content, arr) {
        context = (context === null || context === undefined) ? window : context;
        context.fn = this;
        const result = context.fn(...arr);
        delete context.fn;
        return result;
      };

3、bind

      Function.prototype.bind_ = function (context, ...args1) {
        context = (context === null || context === undefined) ? window : context;
        let _this = this;

        return function (...args2) {
          context.fn = _this;
          const result = context.fn(...[...args1, ...args2]);
          delete context.fn;
          return result;
        };
      };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值