【前端面试】对JavaScript中this的理解总结

本文深入探讨JavaScript中this关键字的指向规则,包括setTimeout、setInterval中的this行为,严格模式与非严格模式的区别,箭头函数中的this特性,以及函数独立调用、对象方法、构造函数和事件处理函数中的this指向。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

setTimeout、setInterval中的this,严格模式和非严格模式下的this,箭头函数中的this,函数独立调用中的this

1.setTimeout、setInterval中的this

var obj ={ 
    fn:function(){
        console.log(this);
    }
}
function fn2(){
    console.log(this);
}
setTimeout(obj.fn, 0);   //Window
setTimeout(fn2, 0);//Window
setInterval( obj.fn,1000 );//Window

从上述例子中可以看到setTimeout,setInterval中函数内的this是指向了window对象,这是由于setTimeout(),setInterval()调用的代码运行在与所在函数完全分离的执行环境上。这会导致这些代码中包含的 this 关键字会指向 window (或全局)对象。

2.严格模式下的this

(1)全局作用域中的this
"use strict"
console.log("this === window",this === window);   //true

在严格模式下的全局作用域中 this 指向window对象

(2)全局作用域中函数中的this
"use strict"
function fn(){
    console.log('fn的this:'+this);
    function fn2(){
        console.log('fn2的this:'+this);
    }
    fn2();    
}
fn();
// fn的this:undefined
// fn2的this:undefined

严格模式下: 在全局作用域中函数的 this 指向 undefined

(3)对象的方法中的this
"use strict"
let name = 'zhaosi';
let obj = {
    name: 'liuneng',
    fn:function(){
        console.log(this.name)
        console.log(this);
    }
}
obj.fn();
//  liuneng
// {name: "liuneng", fn: ƒ}

严格模式下,对象的函数中的this指向该对象

(4)构造函数中的this

"use strict"
function Person( name){
    this.name = name;
    this.say = function(){
        console.log('my name is:'+this.name);
        console.log(this);
    }
}
var lzx = new Person('lzx');
lzx.say();  
//my name is lzx
//Person { name:"lzx", say:f } 

严格模式下,构造函数中的this指向new出来的对象

(5)事件处理函数中的this
"use strict"
var oBtn = document.getElementById("btn");
oBtn.onclick = fn;
function fn(){
    console.log(this);
}
//<button id="btn">点击</button>

3.箭头函数中的this

首先,箭头函数没有自己的this,箭头函数中的this是在定义函数的时候绑定,它会捕获其所在的上下文的this作为自己的this,而不像普通函数那样是在执行函数的时候绑定。

 var a = 10;
var obj = {
    a: 99,
    fn1:()=>{ console.log(this.a) },
    fn2:function(){ console.log(this.a) }
}
obj.fn1(); //10
obj.fn2(); //99

箭头函数this指向它定义时的上下文(在这里是window),而普通函数的this则指向调用它的对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值