原生方法2


改变this指向的三大方法

原理

都是在需要绑定的上下文中添加一个函数,执行函数,删除函数,返回结果。

call

    Function.prototype.xf_call = function (thisArg, ...args) {
        const fn = this

        // 如果要绑定的this是undefined或者null,默认指定为window
        thisArg = thisArg || window
        const key = Symbol()
        thisArg[key] = fn

        // 执行
        const result = thisArg[key](...args)
   
        delete thisArg[key]
        return result
    }

apply

    Function.prototype.xf_apply = function (thisArg, args) {
        if (args instanceof Array) {
            const fn = this
            thisArg = thisArg || window
            const key = Symbol()
            thisArg[key] = fn
            const result = thisArg[key](args)

            delete thisArg[key]

            return result
        }
        throw new Error('apply args must be get a arr')
    }

bind

    Function.prototype.xf_bind = function(thisArg, ...args) {
        const fn = this
        thisArg = thisArg || window
        const key = Symbol()
        thisArg[key] = fn

        return function () {
            const result = thisArg[key](...args)
            delete thisArg[key]
            return result
        }
    }
    
    function a () {
        let name = '牛总'
        console.log('a 函数的 this', this); // a 函数的 this {age: 18, Symbol(): ƒ}
    }

    const obj = {
        age: 18
    }
    
    console.log('a.xf_call(obj, 1, 2, 3)', a.xf_bind(obj, [1, 2, '天涯路尽'], 'i love you')());
    console.log('a.xf_call(obj', a.xf_bind(obj, ['天涯路尽'])());

文章作者: KarlFranz
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 reprint policy. If reproduced, please indicate source KarlFranz !
评论
  目录