改变this指向 call,apply,bind

内置call/apply/bind实现的办法

~ function () {

    /*生成随机函数名:时间戳的方式*/
    function queryRandomName() {
        let time = new Date().getTime();
        return '$ran' + time;
    };

    /*
     * call:改变函数中的THIS指向 
     *   @params
     *      context 可以不传递,传递必须是引用类型值(因为后面要给它加$fn的属性)  
     */
    
    
    /*模拟CALL方法改变函数中的THIS*/
    function changeThisCall(context = window, ...ary) {
        let _this = this,
            result = null,
            ran = queryRandomName();
        context[ran] = _this;
        result = context[ran](...ary);
        delete context[ran];
        return result;
    };

    //APPLY方法
    function changeThisApply(context, arg = []) {
        let _this = this,
            result = null,
            ran = queryRandomName();
        context[ran] = _this;
        result = context[ran](...arg);
        delete context[ran];
        return result;
    } 

    // =>bind方法
    //=>bind方法在IE6~8中不兼容,接下来我们自己基于原生JS实现这个方法
    function myBind(context=window,...arg) {
        let _this = this,
            outerArg = arg;
        return function anonymous(...arg) {
            let innerArg = arg;
            _this.apply(context, outerArg.concat(innerArg));
        }
    };

    // 把方法挂在函数的原型上;
    ["changeThisCall", "changeThisApply","myBind"].forEach(item => {
        Function.prototype[item] = eval(item);
    });
}();
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容