call/apply/bind等源码实现

17 篇文章 0 订阅

call apply源码实现:

首先,call和apply均是function原型上的方法

其实就是把要执行的函数,挂载到要知道this的对象身上,最后在delete到这个属性,即可

如果传null、undeifnd等无效值,默认是指向window

    // call apply模拟
    var a = 10;
    var obj = {
      a: 20
    }
    function test(...params) {
      console.log(this.a, ...params);
    }
    // test.call(null);
    // test.apply(obj,[1,2]);

    Function.prototype.myCall = function (target, ...params) {
      target = target || window;
      target.fn = this;
      target.fn(...params);
      delete target.fn;
    }

    Function.prototype.myApply = function (target, params) {
      if (!Array.isArray(params)) new TypeError('params must be array')
      target = target || window;
      target.fn = this;
      target.fn(...params);
      delete target.fn;
    }

    test.myCall(null, 1, 2);
    test.myApply(obj, [1, 2]);

 

bind 源码实现:

    /*
      * bind模拟
      * 1.函数A调用bind方法时,需要传递的参数o, x, y, z...
      * 2.返回新函数B
      * 3.函数B在执行的时候,具体的功能实际上还是使用的A,只是this指向变成了o,默认是window
      * 4.函数B再执行的时候,传递的参数会拼接到x, y, z的后面,一并在内部传递给A执行
      * 5.new B()  此时产生的对象的构造函数依旧是A,并且o不会起到任何作用
      */ 

    var obj1 = {
      a: 20
    }

    function test1(...params) {
      console.log(this.a, ...params);
    }

    var fn = test1.bind(obj1, 3);
    fn(4);

    
    Function.prototype.myBind = function (target, ...params) {
      target = target || window;
      let self = this;
      let temp = function (){};
      let f = function (...params2) {
        return self.apply(this instanceof temp ? this : target, params.concat(params2));
      }
      temp.prototype = self.prototype;
      f.prototype = new temp();
      // console.log('aa', new temp().constructor)
      return f;
    }

    var fn2 = test1.myBind(obj1, 4);
    fn2();
    new fn2();
    app.addEventListener('click', test1.myBind(obj1, 22, 33));
    // console.log( new fn2().constructor )

 

Object.create原理实现:

    Object.prototype.myCreate = function (obj) {
      let F = function() {};
      F.prototype = obj;
      return new F();
    }

 

instanceof原理实现:

    function myInstanceof(prev, next) {
      if(prev.__proto__ === null) return false;
      if(prev.__proto__ == next.prototype) {
        return true;
      } else {
        return myInstanceof(prev.__proto__, next);
      }
    }

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值