ES6箭头函数及面试题

箭头函数

箭头函数是es6当中对函数的一种全新表示法。其将函数的简洁性发扬到了极致!先来看一个最简单的箭头函数:

let fn = a => a
var m = prompt()
alert(fn(m))

1. 箭头函数写法

一、如果只有一条语句,可以将{}和return省略掉

let fn = a => a+a

//相当于
let fn = function(a){
    
    
    return a+a;
}

二、如果语句为多条,则不可以省略{}和return

let fn = a => {
    
    
	var b = 0;
	console.log(a,b);
}
fn(10)

还有两点需要注意!

一、

  • 当传单个参数的时候,不需要加括号()
var fn = a => a
  • 当传多个值的时候需要加括号
var fn = (a,b)=>a+b

二、

  • 当省略{}和return时,如果返回的内容是一个对象,对象需要用括号()括起来

  • 不加括号的话会是 undefined

var fn = a=>({
     
     a:'你好'})
console.log(fn())

2. 箭头函数不能用于构造函数

先来看构造函数

var ful=function(age){
    
    
    this.age=age;
}
var chl=new ful(18);
console.log(chl.age);//18

改为箭头函数后

var ful = age => {
    
    
    this.age=age;
}
var chl=new ful(18);//ful is not a constructor
console.log(chl.age);

3. 箭头函数没有prototype属性

var fn = () => {
    
    };
console.log(fn.prototype); // undefined

4. 箭头函数不绑定this

箭头函数中没有this 的指向,在箭头函数中this 的指向会指向离他最近的那个作用域

这来看一道面试题:

window.color = "red";
//let 声明的全局变量不具有全局属性,即不能用window.访问
let color = "green";
let obj = {
    
    
    color: "blue",
    getColor: () => {
    
    
        return this.color;//this指向window
    }
};
let sayColor = () => {
    
    
    return this.color;//this指向window
};
console.log(obj.getColor())
obj.getColor();//red
console.log(sayColor())
sayColor();//red

总结

  1. 箭头函数中没有this 的指向,在箭头函数中this 的指向会指向离他最近的那个作用域
  2. 箭头函数不能当做构造函数
  3. 箭头函数中没有 arguments 这个参数

猜你喜欢

转载自blog.csdn.net/m0_55990909/article/details/124752014