Skip to content

this 指向

  1. 对于直接调用的函数来说,不管函数被放在了什么地方,this 都是 window

  2. 对于被别人调用的函数来说,被谁点出来的,this 就是谁

  3. call、apply 时,this 是第一个参数。bind 要优与 call/apply 哦,call 参数多,apply 参数少

  4. 在构造函数中,类中(函数体中)出现的 this.xxx=xxx 中的 this 是当前类的一个实例

  5. 箭头函数没有自己的 this,需要看其外层的是否有函数,如果有,外层函数的 this 就是内部箭头函数的 this,如果没有,则 this 是 window

默认绑定

js
//1、非严格模式
function myfunc() {
  console.log(this)
}
myfunc() //window

//2、严格模式
function fn() {
  'use strict' //严格模式下,禁止this关键字指向全局对象
  console.log(this)
}
fn() //undefined

隐式绑定(属性访问调用,函数被别人调用)

js
function fn() {
  console.log(this.a)
}
const obj = {
  a: 1,
}
obj.fn = fn
obj.fn() //1
js
function fn() {
  console.log(this.a)
}
const obj1 = {
  a: 1,
  fn,
}
const obj2 = {
  a: 2,
  obj1,
}
obj2.obj1.fn() //1

显示绑定(apply\call\bind)

  • apply

func.apply(thisArg, [argsArray])

thisArg 为 undefined 或 null 时指向全局 返回调用有指定 this 值和参数的函数的结果

  • call

function.call(thisArg, arg1, arg2, ...)

返回使用调用者提供的 this 值和参数调用该函数的返回值,若该方法没有返回值,则返回 undefined。

  • bind

function.bind(thisArg[, arg1[, arg2[, ...]]])

  • thisArg:调用绑定函数时作为 this 参数传递给目标函数的值。 如果使用 new (opens new window)运算符构造绑定函数,则忽略该 值。当使用 bind 在 setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。如果 bind 函数的参数列表为空,或者 thisArg 是 null 或 undefined,执行作用域的 this 将被视为新函数的 thisArg。 arg1, arg2, ...:当目标函数被调用时,被预置入绑定函数的参数列表中的参数。
  • 返回:返回一个原函数的拷贝,并拥有指定的 this 值和初始参 数。

new 创建对象

如果函数 constructor 里没有返回对象的话,this 指向的是 new 之后得到的实例

js
function foo(a) {
  this.a = a
}
const f = new foo(2)
f.a // 2

function bar(a) {
  this.a = a
  return {
    a: 100,
  }
}
const b = new bar(3)
b.a //100

箭头函数

编译期间确定的上下文,不会被改变,哪怕你 new,指向的就是上一层的上下文,箭头函数没有自己的 this,需要看其外层的是否有 函 数,如果有,外层函数的 this 就是内部箭头函数的 this,如果没有,则 this 是 window

js
var a = {
  myfunc: function () {
    setTimeout(function () {
      console.log(this) // this是window
    }, 0)
  },
}
a.myfunc() //window

var a = {
  myfunc: function () {
    var that = this
    setTimeout(function () {
      console.log(that) // this是a
    }, 0)
  },
}
a.myfunc() //a对象:{myfunc: ƒ}

// 箭头函数
var a = {
  myfunc: function () {
    setTimeout(() => {
      console.log(this) // this是a
    }, 0)
  },
}
a.myfunc() //a对象:{myfunc: ƒ}

function fn() {
  return {
    b: () => {
      console.log(this)
    },
  }
}
fn().b() //window
fn().b.bind(1)() //window
fn.bind(2)().b.bind(3)() //Number(2)