ES6新特性:箭头函数详解

参考:https://www.runoob.com/w3cnote/es6-function.htmlhttps://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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值