JavaScript this 关键字指向问题以及globalThis

JavaScript this 关键字

面向对象语言中 this 表示当前对象的一个引用。但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。

  • ES2020 在语言标准的层面,引入globalThis作为顶层对象。也就是说,任何环境下,globalThis都是存在的,都可以从它拿到顶层对象,指向全局环境下的this
  • 在方法中,this 表示该方法所属的对象。
  • 如果单独使用,this 表示全局对象。
  • 在定时函数中,this 表示全局对象。
  • 在函数中,在严格模式下,this 是未定义的(undefined)。
  • 在事件中,this 表示接收事件的元素。
  • ES6箭头函数:函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。箭头函数的最大作用就是this指向
  • 改变this指向方法: call() 和 apply() 方法可以将 this 引用到任何对象。
例如在对象中this代表该对象,下面的例子中指向person
// 创建一个对象
var person = {
  firstName: "李",
  lastName : "四",
  id     : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
// 显示对象的数据
document.write(person.fullName()) //李四
单独使用this时代表全局变量
var x = this;
console.log(x)  //window
函数中使用this,默认函数的所属着,此时的this代表myFunction()
function myFunction() {
  return this;     
}
函数在严格模式下使用this,这时候 this 是 undefined。
"use strict";
function myFunction() {
  return this;
}
document.write(myFunction())  //undefined
事件中的 this

在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素:

<button onclick="this.style.display='none'">点我后我就消失了</button>   //button按钮消失
显式函数绑定

在 JavaScript 中函数也是对象,对象则有方法,apply 和 call 就是函数对象的方法。这两个方法异常强大,他们允许切换函数执行的上下文环境(context),即 this 绑定的对象。
在下面实例中,当我们使用 person2 作为参数来调用 person1.fullName 方法时, this 将指向 person2, 即便它是 person1 的方法:

var person1 = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"张",
  lastName: "三",
}
var x = person1.fullName.call(person2); 
document.write(x);  //张三

定时器中的this指向window

var name = 'window';
var obj = {
    name: 'obj',
    fn: function () {
        var timer = null;
        clearInterval(timer);
        timer = setInterval(function () {
            console.log(this.name);   //window
        }, 1000)
    }
请用今天的努力,让明天没有遗憾。
原文地址:https://www.cnblogs.com/cupid10/p/12849866.html