this关键字的行为

this 是执行上下文中很重要的一个组成部分。同一个函数调用方式不同,得到的 this 值也不同。

  1. // 第一个例子
  2. function showThis(){
  3. console.log(this);
  4. }
  5. var o = {
  6. showThis: showThis
  7. }
  8. showThis(); // global
  9. o.showThis(); // o

普通函数的 this 值由“调用它所使用的引用”决定,其中奥秘就在于:我们获取函数的表达式,它实际上返回的并非函数本身,而是一个 Reference 类型。

Reference:用于描述对象属性访问、delete 等。

Reference 类型由两部分组成:一个对象和一个属性值。不难理解 o.showThis 产生的 Reference 类型,即由对象 o 和属性“showThis”构成。

此时,调用函数时使用的引用,决定了函数执行时刻的 this 值。
**
实际上从运行时的角度来看,this 跟面向对象毫无关联,它是与函数调用时使用的表达式相关。

  1. // 箭头函数中的this
  2. const showThis = () => {
  3. console.log(this);
  4. }
  5. var o = {
  6. showThis: showThis
  7. }
  8. showThis(); // global
  9. o.showThis(); // global

我们看到,改为箭头函数后,不论用什么引用来调用它,都不影响它的 this 值。

  1. // 类中的方法
  2. class C {
  3. showThis() {
  4. console.log(this);
  5. }
  6. }
  7. var o = new C();
  8. var showThis = o.showThis;
  9. showThis(); // undefined
  10. o.showThis(); // o

this关键字的机制

函数能够引用定义时的变量,如上文分析,函数也能记住定义时的 this,因此,函数内部必定有一个机制来保存这些信息。
在 JavaScript 标准中,为函数规定了用来保存定义时上下文的私有属性 [[Environment]]。
当一个函数执行时,会创建一条新的执行环境记录,记录的外层词法环境(outer lexical environment)会被设置成函数的 [[Environment]]。

var a = 1;
foo();

在别处定义了 foo:

var b = 2;
function foo(){
    console.log(b); // 2
    console.log(a); // error
}

这里的 foo 能够访问 b(定义时词法环境),却不能访问 a(执行时的词法环境),这就是执行上下文的切换机制了。

JavaScript 用一个栈来管理执行上下文,这个栈中的每一项又包含一个链表。如下图所示:

image.png

当函数调用时,会入栈一个新的执行上下文,函数调用结束时,执行上下文被出栈。
而 this 则是一个更为复杂的机制,JavaScript 标准定义了 [[thisMode]] 私有属性。

[[thisMode]] 私有属性有三个取值。

  • lexical:表示从上下文中找 this,这对应了箭头函数。
  • global:表示当 this 为 undefined 时,取全局对象,对应了普通函数。
  • strict:当严格模式时使用,this 严格按照调用时传入的值,可能为 null 或者 undefined。

非常有意思的是,方法的行为跟普通函数有差异,恰恰是因为 class 设计成了默认按 strict 模式执行。

"use strict"
function showThis(){
    console.log(this);
}

var o = {
    showThis: showThis
}

showThis(); // undefined
o.showThis(); // o

函数创建新的执行上下文中的词法环境记录时,会根据 [[thisMode]] 来标记新纪录的 [[ThisBindingStatus]] 私有属性。
代码执行遇到 this 时,会逐层检查当前词法环境记录中的 [[ThisBindingStatus]],当找到有 this 的环境记录时获取 this 的值。

这样的规则的实际效果是,嵌套的箭头函数中的代码都指向外层 this,例如:

var o = {}
o.foo = function foo(){
    console.log(this);
    return () => {
        console.log(this);
        return () => console.log(this);
    }
}

o.foo()()(); // o, o, o

这里调用三个函数,获得的 this 值是一致的,都是对象 o。

操作 this 的内置函数

Function.prototype.call 和 Function.prototype.apply 可以指定函数调用时传入的 this 值
Function.prototype.bind 它可以生成一个绑定过的函数,这个函数的 this 值固定了参数

function foo(a, b, c){
    console.log(this);
    console.log(a, b, c);
}

foo(1, 2, 3) // window  // 1 2 3
foo.call({}, 1, 2, 3); // {}  // 1 2 3
foo.apply({}, [1, 2, 3]); // {} // 1 2 3
foo.bind({}, 1, 2, 3)(); // {} // 1 2 3

有趣的是,call、bind 和 apply 用于不接受 this 的函数类型如箭头、class 都不会报错。这时候,它们无法实现改变 this 的能力,但是可以实现传参。

const foo = (a, b, c) => {
        console.log(this);
    console.log(a, b, c);
}

foo(1, 2, 3) // window  // 1 2 3
foo.call({}, 1, 2, 3); // window  // 1 2 3
foo.apply({}, [1, 2, 3]); // window // 1 2 3
foo.bind({}, 1, 2, 3)(); // window // 1 2 3

笔记摘自 《重学前端》 —- winter