函数内this指向

46 阅读1分钟

this的指向是函数调用的时候确定的,调用方式不同this指向也不同

调用方式this指向
普通函数调用windows
构造函数调用实例对象 原型对象里面的方法也指向实例对象
对象方法调用该方法所属对象
事件绑定方法绑定事件对象
定时器函数windows
立即执行函数windows
普通函数-->this指向windows
		function fn() {
			console.log('函数this指向'+this);
			//函数this指向[object Window]
		}
		fn()
对象方法-->this指向对象fn
		var fn = {
			sayHi: function () {
				console.log('对象方法的this:' + this);
				//对象方法的this:[object Object]
			}
		}
		fn.sayHi()
构造函数-->this指向这个实例
		function Star() {
			console.log(this);
			//Star {}
		}
		var ldh = new Star();
绑定事件函数-->this指向btn
		var btn = document.querySelector('button')
		btn.onclick = function() {
			console.log('this指向',this);
			//指向btn
		}
定时器函数-->this指向windows
		setTimeout(() => {
			console.log('定时器this指向',this);
			// 定时器this指向 Window
		}, 100);
立即执行函数-->this指向windows
		(function() {
			console.log('立即执行函数',this);
                        //this指向 Window
		})()