全局环境下,指向windows
console.log(this.document === document); // true
函数上下文调用
function f1(){
return this;
}
f1() === window; // true对象中的this
对象内部方法的this指向调用这些方法的对 象,函数的定义位置不影响其this指向,
1. this指向只和调用函数的对象有关。
2. 多层嵌套的对象,内部方法的this指向离被调用
函数最近的对象(window也是对象,其内部对象调
用方法的this指向内部对象, 而非window)。构造函数中this
构造函数中的this与被创建的新对象绑定。DOM事件处理函数
(1)当函数被当做监听事件处理函数时, 其 this 指向触发该事件的元素 (针对于addEventListener事件)
(2)代码被内联处理函数调用时,它的this指向监听器所在的DOM元素,当代码被包括在函数内部执行时,其this指向等同于 *函数直接调用*的情况setTimeout & setInterval
对于延时函数内部的回调函数的this指向全局对象window
箭头函数中的 this
(1)由于箭头函数不绑定this, 它会捕获其所在(即定义的位置)上下文的this值, 作为自己的this值,
function Person() {
this.age = 0;
setInterval(() => {
this.age++;
}, 3000);
}
Var p = new Person();
(2)方法的箭头函数this指向全局window对象,而普通函数则指向调用它的对象,箭头函数没有thisvar obj = { I: 10,
b: () => console.log(this.i, this),
c: function() {
console.log( this.i, this)
}
}
obj.b(); // undefined window{...}
obj.c(); // 10 Object {...}