美文网首页
手写bind实现

手写bind实现

作者: 一懒众衫小小小小 | 来源:发表于2020-07-16 13:37 被阅读0次
    Function.prototype.bind = function(thisArg) {
      if (typeof this !== 'function') return;
      const _self = this;
      const args = Array.prototype.slice.call(arguments, 1)
      const f = function() {
        return Reflect.apply(_self, this instanceof _self ? this : (thisArg || window), args.concat(Array.prototype.slice.call(arguments))); // 注意参数的处理
      }
      f.prototype = this.prototype
      return f
    }
    
    Function.prototype.bind1 = function(thisArg, ...args) {
      if (typeof this !== 'function') return;
      const _self = this;
      const f = function() {
        return Reflect.apply(_self, this instanceof _self ? this : (thisArg || window), args.concat(Array.from(arguments))); // 注意参数的处理
      }
      f.prototype = this.prototype
      return f
    }
    
    function foo(name) {
      this.name = name;
    }
    const obj = {}
    
    const bar = foo.bind1(obj)
    bar('mary') // obj { name: 'mary' }
    const tom = new foo('tom') // foo { name: 'tom' }
    
    Function.prototype.call = function(thisArg, ...args) {
      thisArg.tempFn = this
      const result = thisArg.tempFn(...args)
      Reflect.deleteProperty('tempFn')
      return result
    }
    
    Function.prototype.apply = function(thisArg, ...args) {
      thisArg.tempFn = this
      const result = thisArg.tempFn(args)
      Reflect.deleteProperty('tempFn')
      return result
    }
    

    相关文章

      网友评论

          本文标题:手写bind实现

          本文链接:https://www.haomeiwen.com/subject/ihephktx.html