参考:MDN
本文只讨论在浏览器中的指向
this
在绝大多数情况下,函数的调用方式决定了
this
的值。this
不能在执行期间被赋值,并且在每次函数被调用时this
的值也可能会不同。
在严格模式和非严格模式之间也会有一些差别。
全局环境
无论是否在严格模式下,在全局执行环境中(在任何函数体外部)
this
都指向全局对象。
var a = 12;
this.a; // 12
this; // window
函数(运行时)环境
在函数内部,
this
的值取决于函数被调用的方式。
1. 直接调用
- 非严格模式 ->
window
function fn() { retun this; } fn(); // window
var obj = { prop: 12, fn: function() { return this; } }; var fnObj = obj.fn(); fnObj(); // window: 因为函数 fnObj 是直接调用
- 严格模式 ->
undefined
上面第二个例子在严格模式下也是返回function fn() { "use strict"; return this; } fn(); // undefined
undefined
。
2. 作为对象的方法调用
严格模式/非严格模式 -> 调用方法的对象
var obj = {
prop: 12,
fn: function() {
return this;
}
};
obj.fn(); // obj
var obj = { prop: 12 };
function fn() {
return this;
}
obj.fn = fn;
obj.fn(); // obj
3. 箭头函数
在箭头函数中,
this
与封闭词法环境的this
保持一致。
即书写代码时 this
的指向
var fn = () => this;
fn(); // window
var obj = {
bar: function() {
var x = () => this;
return x;
}
};
var fn = obj.bar();
fn(); // obj
obj.bar()(); // obj
4. 作为构造函数
使用 new
关键字 -> 正在构造的新对象