介绍js中this

定义

this是js的一个关键字,this指向当前执行上下文中的对象。在不同的上下文中,this的值会有所不同。

不同上下文的this指向

全局上下文

在全局执行上下文中,this 指向全局对象。在浏览器中,这个全局对象是 window,在Node.js中则是 global

console.log(this); // 在浏览器中输出 Window 对象
函数上下文 

在普通函数内,this 默认为全局对象(在严格模式下为 undefined)。但是如果通过对象调用一个方法,this 会指向那个对象。

  function showThis() {
    console.log(this);
  }
  showThis();// 在浏览器中输出Window对象或undefined

  const obj = {
    name: 'Tom',
    fn1: function () {
      console.log(this.name);
    }
  };
  obj.fn1(); // 输出'Tom'
构造函数上下文

当使用 new 关键字调用构造函数时,this 指向新创建的实例对象。

function Person(name) {
  this.name = name;
}
const p = new Person('Alice');
console.log(p.name); // 输出'Alice'
箭头函数的上下文

箭头函数不会创建自己的 this 值,它会从外部上下文中继承 this

const obj = {
  value: 42,
  getValue: function() {
    return () => this.value; // 这里的 this 继承自 getValue 的上下文
  }
};
const func = obj.getValue();
console.log(func()); // 输出 42
 function foo() {
   this.value = '111';
   (() => 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

eyuiomvtywn

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

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

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

打赏作者

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

抵扣说明:

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

余额充值