0xarch
I could be myself out there. Bullying, reckless, totally selfish. Doing the things that makes me me. If you ain't who you are, then who the fuck are you?
ConsoleArchives关于
QueryCategoriesCode Snippets6Linux1前端技术6游戏2金句1青岛公交8TagsArchLinux1Chromium1JavaScript8Linux2Node.js4都市:天际线2金句1

本文中所有 Demo 均在 RunJS 中运行。

函数对象本身

当函数作为构造器被调用时,this 指向自身。

function constructor(){
  console.log(this);
}

new constructor();

::: caution 箭头函数不能作为构造器

const arrowCanNotBeConstructor = () => {
  console.log(this);
}

new arrowCanNotBeConstructor();
// TypeError: arrowCanNotBeConstructor is not a constructor

:::

对象本身

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

const object = {
  value: 1,
  logThis: function(){
    console.log(this);
  }
}

object.logThis();

当通过 f.call 调用函数时, this 指向 call 的第一个参数。

const object = {
  value: 1,
  arrowLog: ()=>{
    console.log(this);
  },
  logThis: function(){
    console.log(this);
  }
}

const obj2 = {
  value: 2
}

object.logThis.call(Array.prototype);
object.logThis.call(obj2);

::: note 箭头函数作为方法时,尽管通过 call 调用,其 this 依旧指向 globalThis。 :::

类(ES6)的静态方法指向类本身,实例方法指向实例本身。

class someClass {
  logThis(){
    console.log(this);
  }
  
  static staticLogThis(){
    console.log(this);
  }
}

someClass.staticLogThis();
new someClass().logThis();

globalThis

定义于全局的函数和箭头函数,在作为函数调用时 this 都指向 globalThis

function globalFunction(){
  console.log(this === globalThis); // true
}

const globalArrowFunction = () => {
  console.log(this === globalThis); // true
}

定义于对象上的箭头函数,在作为函数调用时 this 指向 globalThis

const object = {
  value: 1,
  arrowLog: ()=>{
    console.log(this === globalThis);
  }
}

object.arrowLog();
JavaScript 中的 This
发布于2024-12-04
作者0xarch
许可协议CC BY-NC-SA 4.0
ChromeOS Linux 子系统托盘守护进程
都市天际线 DLC 补丁自定义教程
0xarch 的博客