详细解析 JavaScript中的this 与 ES6箭头函数的this

普通的this

  1. 如果单独使用,this 表示全局对象。
  2. 在函数中,this 表示全局对象。
  3. 在函数中,在严格模式下,this 是未定义的(undefined)。
    在这里插入图片描述
  4. 在方法中,this 表示该方法所属的对象。
  5. 在事件中,this 表示接收事件的元素。
    在这里插入图片描述
  6. 类似 call() 、apply()、bind() 方法可以将 this 引用到任何对象。
			var name = "我是window";
			// 单独使用
			console.log(this.name);			//我是window
			
			// 在函数中
			function myFunction() {
				name: "我是myFunction",
				console.log(this.name);		//我是window
			}
			myFunction();
			
			//对象中有自己声明的量
			var myObj1 = {
				name: "我是obj1",
				myfun1: function() {
					console.log(this.name);		//我是我是obj1
				}
			};
			myObj1.myfun1();
			
			//对象的this
			var myObj2 = {
				name: this.name,
				myfun2: function() {
					console.log(this.name);	//我是window
				}
			}
			myObj2.myfun2();
			//使用call apply bind
			myObj2.myfun2.apply(myObj1);	//我是我是obj1
			myObj2.myfun2.call(myObj1);		//我是我是obj1
			myObj2.myfun2.bind(myObj1)();	//我是我是obj1

箭头函数

函数名 = () => {函数体}

  • 没有参数或者参数不止一个时一定要写(),只有一个参数可以不写
    在这里插入图片描述
  • 函数体只有一条语句,可以不用{},默认返回结果;函数体有多个语句, 需要用{},若需要返回值,则自己手动写return
    在这里插入图片描述

使用场景:多用来定义回调函数
划重点:箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,而是在定义的时候处在的对象就是它的this
普通函数,被谁调用this就指向谁。
在这里插入图片描述
箭头函数的this看外层的是否有函数,

  • 如果有,外层函数的this就是内部箭头函数的this,
  • 如果没有,则this是window。

下边列举三个例子:
图1中

  • 直接定义了箭头函数fun函数,fun的this指向window,
  • 将fun作为对象obj的方法,fun的this依旧指向window,
  • 在fun中定义一个兼有函数get,get外部没有函数,所以依旧指向window
    在这里插入图片描述

在图2中

  • 在外部定义了箭头函数fun,fun的指针指向window
  • 在函数demo中将fun作为方法调用,由于fun是定义在外部的,因此fun依旧指向window
  • 在函数demo内部定义箭头函数get,get的外层函数是fun,因此get的指针就与demo相同,demo被对象obj调用,demo的指针指向obj,因此fun的指针也指向obj。
    在这里插入图片描述

图3中

  • 普通函数demo1和箭头函数demo2均为obj的方法
  • 箭头函数get1的外层函数是普通函数demo1,demo1的this指针由调用它的对象决定,因此demo1指向obj,而get1的this指针与外层函数相同,所以get1的this指针也指向obj
  • 箭头函数get2的外层函数是箭头函数demo2,demo2的this指针由它的外层函数决定,但是demo2没有外层函数,因此指向window,而get2的this指针与外层函数相同,所以get2的this指向window
    在这里插入图片描述
发布了131 篇原创文章 · 获赞 451 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/qq_36667170/article/details/105036900