this指向 | 青训营笔记

69 阅读2分钟

这是我参与【第四届青训营】笔记创作活动的第5天

一般函数的this指向

this指向函数的调用者,调用方式不同,this指向也不同,下面是6种常见的this指向

1.普通函数调用

最平常的函数调用,this指向的是window对象

        function fn() {
            console.log("普通函数的this:" , this);//Window
        }
        fn();

2.构造函数调用

this指向实例对象,原型对象里面的方法也指向实例对象

	function Star(uname) {
		this.uname = uname;
		console.log("构造函数的this:" , this);//Star 实例对象
	}
	var yan = new Star('yy');

3.对象方法调用

this指向该方法所述对象

	var obj = {
		sing: function () {
			console.log('对象中的方法的this:' + this);//obj
		}
	};
	obj.sing();

4.事件绑定方法

this指向事件绑定对象

	var btn = document.querySelector("button");
	btn.onclick = function () {
		console.log("事件绑定中的this", this);//[object HTMLButtonElement] 调用的对象
	}

5.定时器函数

this指向window对象

        setInterval(function () {
                console.log('定时器函数中的this:', this);//Window
        }, 1000);

6.立即执行函数

this指向window对象

	(function () {
		console.log("立即执行函数中的this:", this);//Window
	})();

箭头函数this的指向

箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时所处的对象(宿主对象), 即如果一个函数内部有用到this,this指向的不是调用者,而是箭头函数定义时的作用域时的this,而作用域的this即同上面6中方法判断一样,谁调用就指向谁

        var uname = 'kiki';
        var obj = {
            uname: 'yy',
            say: () => {
                console.log(this);//Window
                console.log(this.uname);
            },
            sing: function () {
                console.log(this);//{uname: 'yy', say: ƒ, sing: ƒ}
                console.log(this.uname);
            }
        }
        // say方法是用箭头函数,所以this是指向say定义的作用域,而obj是个对象 构不成作用域,则this指向Window
        obj.say();//kiki
        // sing()是function定义的方法,则谁调用指向谁,则指向obj
        obj.sing();// yy 

obj.say()调用者本来是obj,但say方法是箭头函数,因此this为say定义时的作用域,而obj构不成作用域,只能往外找,从而找到window对象,而window对象上有一个uname属性,值为kiki,故调用obj.say()打印this.uname的结果为kiki

obj.sing()不是箭头函数,因此按照前面6中函数调用找,为对象调用,sing为obj定义的一个方法,故this指向obj,obj对象上有个uname属性,值为yy,故调用obj.sing()打印this.uname的结果为yy