avatar

0xarch

重度抑郁爱好者

目录

站点信息

总字数

18409

分类数

7

标签数

10

总文章

37

运行时长

000 天

构建信息

构建时间

Sun Jul 19 2026

Fewu

3.7.86

Nuwari / NEXTario

1.0

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

函数对象本身

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

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

new constructor();

箭头函数不能作为构造器

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();
JS特性:this
作者0xarch
发布于2024-12-04
许可协议CC BY-NC-SA 4.0