环境对象this指向的总结

111 阅读2分钟

谁调用this指向谁

默认情况下:

普通函数中的this指向window;

方法中的this指向调用者;

事件中函数的this指向事件源;

构造函数中的this指向当前实例对象;

定时器中的this指向window;

自执行函数中的this指向window;

箭头函数中的this指向上级作用域的调用者;(箭头函数中不要随意使用this,观察清楚之后再使用)

箭头函数不可以当做构造函数使用

严格模式

开启严格模式 "use strict";(放到作用域的最开头);

普通函数中的this

正常模式下普通函数中的this指向window,严格模式下普通函数指向undefined;

改变this的指向

1.call方法

函数.call(this的指向,a,b,c,d...)后面的参数是传参用的

函数调用call方法, call回头调用函数执行, 在执行的过程中, 改变this指向

不需要改变this指向时, 写null;

     function fn(a, b, c) {
            console.log(this, a, b, c);
        }
        let obj = {
            uname: '王德发',
            age: 22,
        }
        fn.call(obj, 2, 4, 6); */

        function Father(uname, age) {
            this.uname = uname;
            this.age = age;
        }

        function Son(uname, age) {
            // this.uname = uname;
            // this.age = age;
            Father.call(this, uname, age);
        }
        let obj = new Son('王德发', 22);
        console.log(obj); 

2. apply方法(操作数组时可能会用到)

函数.apply(this的指向,[a,b,c,d...])后面是以数组的方式传参,有几个值数组中就写几个值,传递时会一一对应传递

let arr = [23, 66, 16, 7, 9, 5];
        // let res = Math.max.apply(null, arr);
        let res = Math.max(...arr);
        console.log(res);

不需要改变this指向时, 写null; 剩余运算符...可以展开数组; ...若用来接收值时,表示接收剩余值;

3. bind方法

bind不会执行函数,而是相当于返回了一个改变this之后的函数

函数.bind(this的指向,a,b,c,d...);

function fn(a, b, c) {
            console.log(this, a, b, c);
        }
        let obj = {
            uname: '王德发',
            age: 22,
        }
        let res = fn.bind(obj, 2, 4, 6);
        res(); // 需要再调用一遍