前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >call/apply/bind等源码实现

call/apply/bind等源码实现

作者头像
子夜星辰
发布2022-11-15 16:22:39
2450
发布2022-11-15 16:22:39
举报
文章被收录于专栏:李白偷偷偷猪

call apply源码实现:

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

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

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

代码语言:javascript
复制
    // 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 源码实现:

代码语言:javascript
复制
    /*
      * 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原理实现:

代码语言:javascript
复制
    Object.prototype.myCreate = function (obj) {
      let F = function() {};
      F.prototype = obj;
      return new F();
    }

instanceof原理实现:

代码语言:javascript
复制
    function myInstanceof(prev, next) {
      if(prev.__proto__ === null) return false;
      if(prev.__proto__ == next.prototype) {
        return true;
      } else {
        return myInstanceof(prev.__proto__, next);
      }
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-06-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档