this的指向是调用函数的时候确定的,调用的方式不同确定了this的指向不同,一般指向调用者
1、普通函数:this指向window
function fn() {
console.log("this的指向" + this);
}
fn()//this的指向[object Window]
2、对象的方法:this指向 Object
var obj = {
show: function() {
console.log("this的指向" + this);
}
}
obj.show()//this的指向[object Object]
3、构造函数调用:this指向p1实例对象,原型对象里面的方法也指向实例对象
function People() { }
People.prototype.show = function() { }
var p1 = new People()
4、绑定事件函数,this的指向是事件函数的调用者btn按钮对象
<button>确定</button>
<script>
var btn = document.querySelector("button")
btn.onclick = function() {
console.log("this的指向是" + this);//this的指向是[object HTMLButtonElement]
}
</script>
5、定时器函数 :this的指向也是window
setTimeout(function() {
console.log("定时器this的指向是" + this)
}, 2000);//定时器this的指向是[object Window]
6、立即执行函数 :this的指向也是window
(function() {
console.log("立即执行函数this的指向是" + this)
})()//立即执行函数this的指向是[object Window]