This指向问题

this只有在函数执行的时候才能确定this到底指向谁,一般情况下this的最终指向的是那个调用它的对象

  1. 全局作用域或者普通函数中this指向全局对象window,(注意定时器里面的this指向window)

    console.log(this); // 指向window全局对象
    			
    function fn(){
    	console.log(this);
    }
    fn();			// 指向window全局对象
    			
    setTimeout(function(){
    	console.log(this);
    },1000)			// 指向window全局对象
    
  2. 方法调用中谁调用this指向谁

let user = {
	eat: function() {
		console.log(this);
	}
}
user.eat(); // this指向user这个对象
// ---------------------------------
var btn = document.querySelector('button');
btn.onclick = function() {
     console.log(this); // this指向的是btn这个按钮对象
}
btn.addEventListener('click', function() {
	console.log(this); // this指向的是btn这个按钮对象
})
  1. 构造函数中this指向构造函数的实例
function Fun() {
	console.log(this); // this 指向的是fun 实例对象
}
var fun = new Fun();   // Fun {}
posted @ 2022-04-25 17:04  秋弦  阅读(20)  评论(0编辑  收藏  举报