ES6新特性箭头函数语法以及与ES5普通函数的不同

一、箭头函数语法

ES6标准新增了一种新的函数:Arrow Function(箭头函数)。

x => x * x   
//上面为箭头函数写法,相当于下面原来函数的写法
function (x) {
    return x * x;
}

箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ ... }和return都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }和return:

x => {
    if (x > 0) {
        return x * x;
    }
    else {
        return - x * x;
    }
}

如果参数不是一个,就需要用括号()括起来:

// 两个参数:
(x, y) => x * x + y * y

// 无参数:
() => 3.14

// 可变参数:
(x, y, ...rest) => {
    var i, sum = x + y;
    for (i=0; i

如果要返回一个对象,就要注意,如果是单表达式,这么写的话会报错:

x => ({ foo: x })

二、箭头函数与普通函数(function)区别

1、写法上的不同

使用ES6箭头函数语法定义函数,将原函数的“function”关键字和函数名都删掉,并使用“=>”连接参数列表和函数体。当函数参数只有一个,括号可以省略;但是没有参数时,括号不可以省略。

function fun(x, y) {
    return x + y;
}

(a, b) => {
    return a + b
}
//省略写法
a =>  a 

2、普通函数的参数是arguments,而箭头函数是arg

箭头函数不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。

const test1=(...numbers)=>{
  console.log(numbers)      
  console.log(arguments)
}
const test2=function(){
  console.log(arguments)
}
test1(123);//分别输出 [123]  报错
test2(123);//分别输出 Arguments 

3、函数内this的指向不同

在箭头函数出现之前,每个新定义的普通函数(function)都有他自己的this值,箭头函数没有自己的 this,它里面的 this 是继承所属上下文中的 this。
由于箭头函数没有自己的this指针,通过call()、apply()方法调用时,第一个参数会被忽略。
关于call()和apply():

JavaScript中的每一个Function对象都有一个apply()方法和一个call()方法apply调用一个对象的一个方法,用另一个对象替换当前对象。例如:B.apply(A, arguments);即A对象调用B对象的方法。func.apply(thisArg, [argsArray])
call调用一个对象的一个方法,用另一个对象替换当前对象。例如:B.call(A,args1,args2);即A对象调用B对象的方法。func.call(thisArg, arg1, arg2, ...)

//使用function定义的函数
function foo(){
    console.log(this);
}

foo(); //Window

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

foo(); //Window

4、function是可以定义构造函数的,而箭头函数是不行的

/使用function方法定义构造函数
function Dog(name, color){
    this.name = name;
    this.color= color;
}
var newDog=  new Dog('demon', black);
console.log(newDog); //{name: 'demon', color: black}

//尝试使用箭头函数
var Dog= (name, color) =>{
    this.name = name;
    this.color= color;
};
var newDog= new Dog('demon', black); //Uncaught TypeError: Dogis not a constructor

你可能感兴趣的:(ES6新特性箭头函数语法以及与ES5普通函数的不同)