修改this指向

2019-03-06  本文已影响0人  晚溪呀

传参

不传参数时 this 默认指向 window
call 接受散的数据,如果是数组视为一条数据
apply 只能是数组
bind 接受散的数据,如果是数组视为一条数据

执行问题

callapply 都会主动执行
bind 不会主动执行

修改调用函数 this 指向的对象,调用函数的实参依次写在后面

任意对象的原型上的方法,要取这个方法的调用者,直接 this

字符串可以解析字符串
setTimeOut('fn(1, 2, 3)', 1000);
时间一到就把字符串 去掉 函数又是立即执行的

兼容bind方法 (IE8 及其一下不支持bind方法)

        // 没有bind方法才调用
        if (!Funtion.prototype.bind) {
            Function.prototype.bind = function () {

                // 拿到修改this指向的对象
                var bindThis = arguments[0];

                // 拿到后面的所有参数
                var arg = Array.prototype.slice.call(arguments, 1);

                // 拿到调用者
                var that = this;

                return function () {
                    that.apply(bindThis, arg);
                }
            }
        }
上一篇 下一篇

猜你喜欢

热点阅读