function bar() {
console.log(this);
// strict: undefined
// non-strict: window
}
function foo() {
function fun() {
console.log(this);
// strict: undefined
// non-strict: window
}
fun();
}
bar();
foo();
结论:严格模式下是 undefined,非严格模式下是 window
对象的方法中的 this
var obj = {
name: 'peter',
foo: function () {
return this.name;
}
}
console.log(obj.foo()); // 都是 peter
结论:this 指向调用函数的对象实例
构造函数的 this
function A() {
this.foo = '~foo~';
this.bar = function () {
console.log(this.x); // 都是 x
return this.foo;
}
}
var o2 = new A();
o2.x = 'x';
console.log(o2.bar()); // 都是 ~foo~
结论:this 指向构造函数对应创建的对象
事件处理函数中的 this
outElement.onclick = function (e) {
console.log(this) // 点击里面元素,打印 out element
}
inElement.onclick = function (e) {
console.log(this) // 点击里面元素,打印 in element
}
浏览器版本:Mac Chrome 75
全局作用域下访问 this
结论:一样指向 window
全局方法里的 this
结论:严格模式下是 undefined,非严格模式下是 window
对象的方法中的 this
结论:this 指向调用函数的对象实例
构造函数的 this
结论:this 指向构造函数对应创建的对象
事件处理函数中的 this
结论:两种模式,this 指向事件绑定的元素(即 e.currentTarget)
内联事件处理器
结论:严格模式下,内联函数的this 是 undefined,非严格模式下指向 window