JavaScript中this指向

JavaScript中,this 的指向是一个相对复杂且容易混淆的概念。它的指向取决于函数调用的方式和上下文。以下是一些常见的情境,以及在这些情境中 this 的指向:

1.全局上下文:

在全局作用域中,this 通常指向全局对象。在浏览器环境中,这个全局对象是 window

console.log(this); // Window

2.函数直接调用:

当函数被直接调用时(而不是作为对象的方法或构造函数),this 通常指向全局对象。

function myFunction() {  
    console.log(this); // Window
}  
myFunction();

3.对象方法调用:

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

const myObject = {  
    myMethod: function() {  
        console.log(this); // myObject
    }  
};  
myObject.myMethod();

4.构造函数调用:

当函数作为构造函数使用(通过 new 关键字)时,this 指向新创建的对象实例。

function MyConstructor() {
    this.myProperty = 'Hello';  
}  
const instance = new MyConstructor();  
console.log(instance.myProperty); // 'Hello'

5.箭头函数:

箭头函数不绑定自己的 this,而是捕获其所在上下文的 this 值。这意味着在箭头函数中,this 的值将始终是其封闭执行上下文的 this 值。

const myObject = {  
    myMethod: () => {  
        console.log('123'); 
    }  
};  
myObject.myMethod(); // 123

6.事件监听器和其他回调:

在事件监听器、定时器回调等中,this 的指向Window

setTimeout(function() {  
    console.log(this); // Window
}, 1000);

如果需要特定的 this 上下文,可以使用 .bind().call().apply() 方法来明确设置。

const myObject = {  
    myMethod: function() {  
        console.log(this); // myObject
    }  
};  
  
setTimeout(myObject.myMethod.bind(myObject), 1000); // 使用 .bind() 来绑定 this

7.严格模式 (“use strict”):

在严格模式下,全局上下文中 this 是全局对象。函数直接调用时,thisundefined

"use strict";
console.log(this); // Window
function fn() {
  console.log(this); // undefined
}
fn();
  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

剑九 六千里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值