this == window
function dd(){this == window;return this}
dd() == window
- 方法内使用use strict,this是undefined的
function f2() {
'use strict';
return this;
}
f2() === undefined;
function f2() {
'use strict';
this.a='abc'
return this;
}
f2() == undefined
- 函数链式调用时(使用了 . 或者[]),this为调用前面对象的环境
var o = {
prop: 37,
f: function() {
return this.prop;
}
};
console.log(o.f());
- 函数使用了new操作符,生成新对象,this为新对象内的环境
function Foo () {
this.x = 1;
}
var foo = new Foo();
foo.x
- 箭头函数不包含this, 箭头函数的执行上下文的判定,就在其定义的时刻决定
function tt(){
var aa= ()=>{console.log(this);}
aa();
}
tt()
function Foo () {
this.x = 1;
}
Foo.prototype.print = () => {
console.log(this);
}
new Foo().print();