The this point of the arrow function of es6 grammar

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		
		<script>
            	// 箭头函数基础语法  () 里填形参  fun()和普通函数一样写实参
			// 大括号里写执行语句
			
			let fun = (a,b) => {
				console.log(a + b);
			}
			
			fun(5,6)
			
			// 如果执行语句就一行,大括号可省略
			let funs = (a,b) => console.log(a + b);
			funs(6,7)
			
			// 如果形参就一个,小括号可省略
			let funse = a => console.log(a)
			funse(6)







			// 一:全局作用域下this指向
			// 1:普通函数
			// function global(){
			// 	console.log(this);//window
			// }
			// global();
			// 2:箭头函数
			// const global = ()=>{
			// 	console.log(this);//window
			// }
			// global();
			
			
			// 二:对象里面的this指向
			// 1:普通函数
			// const Person = {realname:"张三",age:19,
			//    say:function(){
			// 	   console.log(this.realname);//当前的对象 "张三"
			//    }
			// }
			// Person.say();
			
			// 2:箭头函数
			// const Person = {realname:"张三",age:19,
			//    say:()=>{
			// 	   console.log(this);//window
			//    }
			// }
			// Person.say();
			
			// 三:构造函数的this指向
			// 1:普通函数
			
			// function  Person(realname,age){
			// 	this.realname = realname;
			// 	this.age = age;
			// 	this.say = function(){
			// 		console.log(this);
			// 	}
			// }
			// const P1 = new Person("张三",19);
			// P1.say();
			
			// const P2 = new Person("李四",19);
			// P2.say.call(P1);//原来李四,现在是张三 call和apply改变this指向,区别传输参数的区别
			
			
			// 2:箭头函数
			
			// function  Person(realname,age){
			// 	this.realname = realname;
			// 	this.age = age;
			// 	this.say = ()=>{
			// 		console.log(this);
			// 	}
			// }
			// const P1 = new Person("张三",19); 
			// P1.say();

			// const P2 = new Person("李四",19);
			// P2.say.call(P1);//不能改变箭头函数的this指向
			
			
			// 总结:普通函数与箭头函数this的区别
			// 1:普通的函数this与调用者有关,调用者是谁就是谁;
			// 2:箭头函数的this与当时定义的上下文的this有关,this是静态的一旦定义了就无法改变
			// 箭头函数的this说白了就是谁包含他,他就指向谁,全局下就window ,函数下,就函数,但函数如果要是指向window他也是window 除了构造函数是实例化对象
			
		</script>
	</body>
</html>

Guess you like

Origin blog.csdn.net/tea_tea_/article/details/126888948