跳至主要內容
this

this 是函数运行时的上下文对象,不由定义位置决定,而由调用方式决定。通俗说:谁调用函数,this 就指向谁(箭头函数除外)。

1. this 的指向

函数执行时会在内部创建两个特殊变量:

  • arguments:实参的类数组对象
  • this:当前执行上下文中的 this 绑定
function test() {
  console.log(this);
}

const objA = {
  a: test,
  b: {
    c: test,
  },
};

test();       // window(浏览器)/ global(Node)
objA.a();     // objA
objA.b.c();   // objA.b(只看直接调用者,不看外层对象)

Mr.Ding大约 3 分钟javascriptthiscallapplybind