ES6---箭头函数()=>{} 与function的区别、 this遗留问题的解决

# 1.箭头函数与function定义函数的写法:

//function
function fn(a, b){
	return a + b;
}
//arrow function
var foo = (a, b)=>{ return a + b };

# 2.this的指向:

使用function定义的函数,this的指向随着调用环境的变化而变化的,而箭头函数中的this指向是固定不变的,一直指向的是定义函数的环境。

<mark>使用function定义的函数中this指向是随着调用环境的变化而变化的</mark>

//使用function定义的函数
function foo(){
	console.log(this);
}
var obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }

<mark>明显使用箭头函数的时候,this的指向是没有发生变化的。</mark>

//使用箭头函数定义函数
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window

# 3.构造函数

<mark>function是可以定义构造函数的,而箭头函数是不行的。</mark>

//使用function方法定义构造函数
function Person(name, age){
	this.name = name;
	this.age = age;
}
var lenhart =  new Person(lenhart, 25);
console.log(lenhart); //{name: 'lenhart', age: 25}

//尝试使用箭头函数
var Person = (name, age) =>{
	this.name = name;
	this.age = age;
};
var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructor

# 4.变量提升

由于js的内存机制,function的级别最高

而用箭头函数定义函数的时候,需要var(let const定义的时候更不必说)关键词,而var所定义的变量不能得到变量提升,故箭头函数一定要定义于调用之前!

foo(); //123
function foo(){
	console.log('123');
}

arrowFn(); //Uncaught TypeError: arrowFn is not a function
var arrowFn = () => {
	console.log('456');
};

# this 遗留问题

下面代码,无法获取期望的值

 let hd = {
     name : "ac" , 
     get : function() {
         return function()  { // a
             return this.name; 
         } ; 
     } 
 } ; 
 let a = hd.get() ;
 console.log(a());

undefined

解决

 let hd = {
     name : "ac" , 
     get : function() {
         return () => { // a
             return this.name; 
         } ; 
     } 
 } ; 
 let a = hd.get() ;
 console.log(a());

全部评论

相关推荐

秋招投简历提醒助手:个人经验是,一般面二十场左右就会进入侃侃而谈阶段。我今年七月末的时候开始的第一次面试,都是很多不会,回复很慢。后面慢慢迭代,到九月中的时候基本上面啥说啥,很放松的状态
远程面试的尴尬瞬间
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务