在前端面试的时候,经常会被问到this的指向问题。下面有一道面试题const a = { b() {} } , const c = a.b c的this指向什么 ----->window可能这会儿还不太明白,看完下面的介绍就会知道这道题的答案为什么是window。
1.this的简单介绍
在 JavaScript 中,关键字 this是一个特殊的对象引用,它指向当前正在执行的代码所属的对象。this 的值在函数执行时动态确定,取决于函数的调用方式。具体来说,this 可能有以下几种不同的取值:
2.常见的this指向
常见的5种情况,分别是对象的方法、构造函数内部、事件处理函数、普通全局函数、箭头函数。下面就对这几种情况做简单的介绍。
1.对象的方法---被哪个对象调用this就是谁
let obj = {
a: 1,
run() {
console.log(this.a);
console.log(this);
}
}
// run 里面的this 就是 obj
obj.run();
// 在函数执行的时候确定的
let fn = obj.run;
//fn 全局函数--this -window
fn();
2.构造函数内部--(new +构造函数-->创建对象)构造函数内部的this 就是指 new的时候创建的对象
function Dog(name) {
this.name = name
console.log(this);
}
let d1 = new Dog('白白');
console.log(d1);
3.事件处理函数--给谁添加的事件 this 就是谁。
dom0级事件-->btn.onclick = function(){} dom2级事件-->btn.addEventListenr('click',function(){})
<button></button>
<script>
let btn = document.querySelector('button');
btn.onclick = function () {
console.log(this);//
}
btn.addEventListener('click', function () {
console.log(this);
})
</script>
4.普通全局函数--(没有归属--看不出被谁调用属于谁)匿名函数 ---window
function test() {
// Window
console.log(this);
}
test();
setTimeout(function () {
// Window
console.log(this);
}, 1000);
let arr = [1, 2, 3];
arr.forEach(function () {
// Window
console.log(this);
})
5.箭头函数 .没有自己的this,跟上下文一致
document.addEventListener('click', function () {
console.log(this);//doc
setTimeout(() => {
console.log(this);//doc
}, 1000);
})