zl程序教程

您现在的位置是:首页 >  工具

当前栏目

call/apply/bind等源码实现

源码 实现 call apply bind
2023-06-13 09:15:11 时间

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);
      }
    }