参考:https://www.runoob.com/w3cnote/es6-function.html;https://www.jianshu.com/p/87008f4f8513
ES6的箭头函数提供了一种更加简洁的函数书写方式。基本语法是:参数=>函数体,如常见的:
const fff=name=>console.log(name)
//const 函数名=参数=>内容
例如:
var f = v => v;
//等价于
var f = function(v){
return v;
}
f(1); //1
如果函数的参数只有一个,不需要使用( )包起来:
const greet = name => `Hello ${name}!`;//const声明变量不是指值不变,而是指存值的地址不变
greet('Asser');
空参数列表需要写( ),不写( )代表参数只有一个:
const sayHi = () => console.log('Hello Udacity Student!');
多个参数需要写( ):
var f = (a,b) => a+b;
f(6,2); //8
const orderIceCream = (flavor, cone) => console.log(`Here's your ${flavor} ice cream in a ${cone} cone.`);
orderIceCream('chocolate', 'waffle');//调用
一般箭头函数都只有一个表达式作为函数主题,在函数主体周围没有{ },自动返回表达式:
const upperizedNames = ['Farrin', 'Kagure', 'Asser'].map(
name => name.toUpperCase()
);
但是如果箭头函数的主体内需要多行代码, 则需要使用常规主体语法:它将函数主体放在{ }内需要使用 return 语句来返回内容:
var f = (a,b) => {
let result = a+b;
return result;
}
f(6,2); // 8
const upperizedNames = ['Farrin', 'Kagure', 'Asser'].map( name => {
name = name.toUpperCase();
return `${name} has ${name.length} characters in their name`;
});
当箭头函数要返回对象的时候,为了区分于代码块,要用 () 将对象包裹起来:
// 报错
var f = (id,name) => {id: id, name: name};
f(6,2); // SyntaxError: Unexpected token :
// 不报错
var f = (id,name) => ({id: id, name: name});
f(6,2); // {id: 6, name: 2}
箭头函数里面没有 this 对象,没有 this、super、arguments 和 new.target 绑定.
箭头函数体中的 this 对象,是定义函数时的对象,而不是使用函数时的对象。
var func = () => {
// 此时的 this 是外层的 this 对象,即 Window
console.log(this)
}
func(55) // Window
var func = () => {
console.log(arguments)
}
func(55); // ReferenceError: arguments is not defined
function fn(){
setTimeout(()=>{
// 定义时,this 绑定的是 fn 中的 this 对象
console.log(this.a);
},0)
}
var a = 20;
// fn 的 this 对象为 {a: 19}
fn.call({a: 18}); // 18