关于 this

关于 this

总结

关于 this 的总结:

  1. 沿着作用域向上找最近的一个 function(不是箭头函数),看这个 function 最终是怎样执行的;
  2. this 的指向取决于所属 function 的调用方式,而不是定义;
  3. function 调用一般分为以下几种情况:
    1. 作为函数调用,即:foo()
      1. 指向全局对象,注意严格模式问题(严格模式下,全局的 this,指向 undefined)
    2. 作为方法调用,即:foo.bar() / foo.bar.baz()
      1. 指向最终调用这个方法的对象
    3. 作为构造函数调用,即:new Foo()
      1. 指向一个新对象 Foo{}
    4. 特殊调用,即:foo.call() / foo.apply() / foo.bind()
      1. 参数指定成员
  4. 找不到所属的 function,就是全局对象
    1. var obj = { foo: () => { console.log(this) }},此处 this 指向 window

例题

var length = 0
function fn() {
  console.log(this)
  console.log(this.length)
}

const obj = {
  length: 5,
  method(fn) {
   fn()
   arguments[0]()
  }
}

obj.method(fn, 1, 2)

解析

var length = 0
function fn() {
  console.log(this) // => [fn, 1, 2]
  console.log(this.length) // 3
}

const obj = {
  length: 5,
  method(fn) {
   fn() // => window this.length 10
   // arguments => 实参列表 => [fn, 1, 2]
   arguments[0]() // 可理解成是 arguments.0(), 所以 fn 是由 arguments 调用
  }
}

obj.method(fn, 1, 2)

箭头函数

const obj1 = {
  foo() { // 沿着作用域向上找,最近的一个 function 是 foo,看它怎样执行的 obj1.foo(),所以 this 指向 obj1
    return () => { // 箭头函数和 this 无关,可简单把 => 当成 if 或 for 循环,和其内部的 this 无关,
      console.log(this) // obj1
    }
  }
}

obj1.foo()()
// class 中的 this,实际还是构造函数中的 this,class 只是语法糖而已
class Person {
  say = () => {
    console.log(this) //  => Person 
  }
}

const a = new.Person()
a.say()

转换成 es5

function Person() {
  this.say = () => {
    console.log(this)
  }
}
posted @ 2022-06-30 13:55  小小紫苏  阅读(25)  评论(0)    收藏  举报