1.普通函数 this 指向 window
function fn(){
console.log(this)
}
2.定时器函数 this 指向 window
setInterval(function(){
console.log(this);
},1000)
3.立即执行函数 this 指向 window
(function(){
console.log(this);
})()
4.对象的方法 this 指向 对象
var o = {
say:function(){
console.log(this);
}
}
o.say();
5.构造函数 this 指向 实例对象
function Star(name){
this.name = name;
}
Star.prototype.say = function(){
console.log(this.name);
}
var star = new Star();
star.say()
6.绑定事件函数 this 指向 函数的调用者
btn.onclick = function(){
console.log(this);
}
7.call,apply,bind 都可以改变函数内部的this指向(第一参数)
区别点:
1.call和apply会调用函数,并且改变函数内部this指向,可用于继承
2.call和apply传递的参数不一样,call第二参数接受的是一个参数列表 apply第二参数需要传的是参数数组
3.bind不会立即调用函数,可以改变函数内部this指向 (bind不兼容IE6-8)
8.箭头函数 this指向上级作用域(箭头函数不绑定this)
var a = 0;
let obj = {
a: 1,
fn: () => {
setTimeout(() => {
console.log(this.a) // 此时这里的this.a相当于window.a
});
}
};
obj.fn();//0 此时this向上一级作用域fn查找,而fn也是箭头函数,故fn里面的this指向上级作用域window