this 的指向问题
// 1 this 在函数中 是指向 window 的 因为 window 调用了这个函数
function fun (){
console.log(this);
}
fun(); // Window
// 2 this 在对象的指向 指向的是 obj 谁调用 this 就指向谁
var obj = {
name :"andy",
sayHi :function(){
console.log(this);
that = this;
}
}
obj.sayHi();
console.log(that === obj);
// 3 this 在构造函数中的指向是 ff 还是调用者
function Fn(){
console.log(this);
that = this;
}
var ff = new Fn();
console.log(that === ff);
- 作为纯粹的函数调用 this指向全局对象window
- 作为对象的方法调用 this指向调用对象
- 作为构造函数被调用 this指向新的对象
- call,apply,bind方法调用 this指向第一个参数
- 定时器中的函数 this指向全局对象window
- ES6箭头函数中 this指向父级的this