Skip to content

JS 中的 this #21

@hashdrinker

Description

@hashdrinker

this 的值是在预编译阶段指定的。

全局上下文中的 this

console.log(this);

全局上下文中的 this 比较不统一,建议不要在全局上下文中使用 this。

全局上下文中的 this
非严格模式 严格模式
ES6 Module   undefined
CommonJS Module {} {}
浏览器(Chorme) window 对象 window 对象

函数上下文中的 this

函数上下文中的 this 与调用方式有关。

1.以普通函数的方式调用

function x () {
  console.log(this);
}

x();

这里的 this 指向全局对象,严格模式下,禁止 this 指向全局对象。

以普通函数的方式调用
非严格模式 严格模式
ES6 Module   undefined
CommonJS Module global 对象 undefined
浏览器(Chorme) window 对象 undefined

2.以对象方法的方式调用

function x () {
  console.log(this === o); // true
}

var o = {
  x,
}

o.x();

这里的 this 指向方法所属对象。在这里可以看出,this 不是指向函数调用的上下文,也不是指向其中的变量对象(作用域)。

以构造函数的方式调用

function X () {
  console.log(this);
}

new X();

构造函数中的 this 指向实例化的对象。

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions