Fork me on GitHub

隐式绑定和显式绑定实现一个apply

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
        }

  

posted @ 2021-05-05 20:12  我站在山顶上  阅读(72)  评论(0编辑  收藏  举报