apply作用是改变this的指向。在js中有两种方式改变this的指向。一种是显式的也就是apply、call和bind;另外一种就是隐式的。

因此手动实现apply也就至少有两种方法。

利用隐式绑定。

        Function.prototype.myapply1 = function(target, args){
           if(typeof args === 'undefined' || args === null) {
               args = []
           }
           if(typeof target === 'undefined' || target === null) {
               target = window
           }

           target = new Object(target)

           const targetkey = 'targetkey'
           target[targetkey] = this
           const result = target[targetkey](...args) // 借助隐式绑定实现this执行改写
           delete target[targetkey]
           return result
        }

  利用显式绑定,借助call或者bind

// 利用显示绑定 借助call
        Function.prototype.myapply2 = function(target, args){
            if(typeof args === 'undefined' || args === null) {
               args = []
           }
           if(typeof target === 'undefined' || target === null) {
               target = window
           }
           const result = this.call(target, ...args)
           return result
        }

  

相关文章:

  • 2021-11-10
  • 2022-12-23
  • 2021-12-13
  • 2021-07-25
  • 2021-05-18
猜你喜欢
  • 2021-07-21
  • 2021-12-22
  • 2022-01-31
  • 2022-12-23
  • 2021-12-28
  • 2022-01-13
  • 2022-12-23
相关资源
相似解决方案