Skip to content

This 指向 ​

JS 只有词法作用域没有动态作用域,this 在函数调用时被绑定,其值与函数声明位置无关,只取决于函数的调用方式。

调用方式 ​

  • 作为独立函数调用
  • 作为对象方法调用
  • 作为构造函数调用
  • 通过 apply 和 call 方法来调用

绑定规则 ​

需要先找到函数具体的调用位置,再判断应用下面四条规则中的哪一条。

默认绑定 ​

函数作为独立函数调用时,使用的是默认绑定。非严格模式下,默认绑定 this 为全局对象 window,严格模式下,this 为 undefined。

注意,只看函数体本身是否处于严格模式。此例中 fn() 在严格模式下执行,但 fn 的函数体是在非严格模式下,因此 this 值为 window。

js
function fn() {
  console.log(this)
}
(function(){
  'use strict'
  fn() // window
}())

隐式绑定 ​

函数作为对象的方法调用时,使用隐式绑定,this 为调用该方法的对象。对象属性引用链中,只有最后一层在调用位置中起作用,所以直接看最后一层是怎么调用的。

js
const o = {
  n: 1,
  a: {
    n: 2,
    fn() {
      console.log(this.n)
    }
  }
}
o.a.fn() // 2

注意隐式绑定可能会丢失 this 值。

js
const n = 1
const o = {
  n: 2,
  fn() {
    console.log(this.n)
  }
}
setTimeout(o.fn, 100)
// 打印 1,因为 setTimeout 内部会将传入的函数作为独立函数调用

显式绑定 ​

通过 apply、call 和 bind 将指定对象作为 this 的绑定对象。

注意,如果将 null 或 undefined 作为 this 的绑定对象传入 call、apply 或 bind,则这些值会被忽略,实际应用的是默认绑定。

硬绑定 ​

用一个包裹函数封装 apply 或 call,这样 this 绑定值将不能再被修改,JS 已原生提供了硬绑定的方案(bind)。

软绑定 ​

硬绑定降低了函数灵活性,无法再使用隐式或显式绑定来修改 this。软绑定会检查调用时的 this,如果是全局对象或 undefined,则把指定对象作为 this,否则不修改 this。

js
Function.prototype.softBind = function (obj, ...args) {
  const fn = this
  const bound = function () {
    return fn.apply((!this || this === globalThis ? obj : this), 
    [...args, ...arguments])  
  }
  bound.prototype = Object.create(fn.prototype)
  return bound
}

new 绑定 ​

使用 new 运算符调用构造函数,this 为新建的对象实例。

优先级 ​

new 绑定 > 显示绑定 > 隐式绑定 > 默认绑定

按此顺序逐个进行判断,注意箭头函数的 this 继承自外层函数的 this 值。