理解JS中的this

理解JS中的this

根据W3C的文章,JS中的this的内容可以分为以下几种情况:

  1. 方法中的this(this in method)
  2. 单独的this(this alone)
  3. 一般情况下函数中的this(this in a Function default)
  4. 严格模式下函数中的this(this in a Function strict)
  5. 事件处理函数中的this(this in Event Handler)

1. 类方法中的this

在方法中,this指代方法的“所有者”,即声明该方法的对象。举例来说:

var person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

fullName这个方法中的this指代的就是person这个对象。

2. 单独的this

所谓单独的this,就是不处于任何对象中的this(注意函数也是对象)。

此时,this指向的是Global对象。在浏览器中,Global对象就是[Object Window]。在node中,Global对象就是[Object global]

3. 默认情况下函数中的this

当没有使用严格(strict)模式时,函数中的this默认被绑定(bind)为函数的“所有者”,也就是Global对象。同上,在浏览器中,Global对象就是[Object Window]。在node中,Global对象就是[Object global]

4. 严格模式(use strict)下函数中的this

严格模式中禁止默认绑定this,因此,严格模式下的this的默认值为undefined

5. 事件处理器中的this

在HTML的事件处理器中,this指代触发该事件的HTML元素。

Author: LeoB_O
Link: https://leob-o.github.io/2019/02/01/this-in-JS/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.