2024面试常问的this指向 问题总结

96 阅读2分钟

1.全局环境中的this:在全局环境中(非严格模式下),this指向全局对象,也就是window

console.log(this); // window

2.函数调用中的this:当函数作为普通函数调用时,this指向全局对象(非严格模式下)或者undefined(严格模式下)

function test() {
    console.log(this);
}
test(); // window 或 undefined(严格模式)

3.方法调用中的this:当函数作为对象的方法被调用时,this指向调用该方法的对象。

var obj = {
    method: function() {
        console.log(this);
    }
};
obj.method(); //this指向 obj

4. 构造函数中的this:当函数作为构造函数使用时,this指向新创建的对象。。

function Test() {
    this.x = 10;
    console.log(this);
}
//当使用 new 关键字调用函数时,函数中的 this 一定是JS创建的新对象。
var obj = new Test(); // Test { x: 10 }

5. 箭头函数没有自己的this,它的this是继承自外层代码块,它的指向永远指向箭头函数外层的 this

        function fn() {
            console.log(this);
 
            let fn1 = () => {
                console.log(this);
            }
            fn1(); //this->window
        }
        
        fn();//this->window
 
//因为fn函数中this的指向是window
//所以fn1箭头函数this指向fn函数也就是间接指向window
 

6. 在js中,callapplybind都是可以改变函数运行时this指向的方法,它们都是Function.prototype的方法。

call方法call方法的第一个参数会被作为被调用函数运行时的this值。后续参数则作为函数的参数传入

 function greet() {
    console.log(this.name);
}
var person = { name: 'Alice' };
greet.call(person); // 输出 "Alice"

apply方法apply方法的作用和call方法类似,不同之处在于apply接受两个参数,第一个参数作为函数运行时的this值,第二个参数是一个数组,数组中的元素将作为函数的参数传入

function greet(greeting, punctuation) {
    console.log(greeting + ', ' + this.name + punctuation);
}
var person = { name: 'Bob' };
greet.apply(person, ['Hello', '!']); // 输出 "Hello, Bob!"

bind方法bind方法创建一个新的函数,当这个新函数被调用时,bind的第一个参数将作为它运行时的this,之后的一序列参数将会在传递的实参前传入作为它的参数

function greet() {
    console.log(this.name);
}
var person = { name: 'Charlie' };
var boundGreet = greet.bind(person);
boundGreet(); // 输出 "Charlie"
  • [ 总结]
  • 谁调用this就指向谁!