ES6之箭头函数(Arrow Function)

原文:本文链接:https://blog.csdn.net/kaelyn_X/article/details/78437540

箭头函数(Arrow Function)
  目录:

箭头函数Arrow Function
语法
单一参数的单行箭头函数
多参数的单行箭头函数
多行箭头函数
无参数箭头函数
this 穿透
程序逻辑注意事项
编写语法注意事项
语法
单一参数的单行箭头函数
  用法:arg => statement

const fn = foo => `${foo} hello`; // means retuen `foo + 'hello'`
1
2
  常用于简单的处理函数,比如过滤:

let array = ['a', 'bc', 'def', 'ghij'];
array = array.filter(item => item.length >= 2); // bc, def, ghij
1
2
3
多参数的单行箭头函数
  用法:(arg1, arg2) => statement

const fn = (foo, bar) => foo + bar
1
2
  常用于数组的处理,如排序:

let array = ['a', 'bc', 'def', 'ghij'];
array = array.sort((a, b) => a.length < b.length); // ghij, def, bc, a
1
2
3
多行箭头函数
  用法:args.. => {statement}

foo => {
return 'hello world';
}

(foo, bar) => {
return foo + bar;
}
1
2
3
4
5
6
7
8
无参数箭头函数
  用法:() => statement

const greet = () => 'hello world';
1
2
this 穿透
  箭头函数用于将函数内部的 this 延伸至上一层作用域中,即上一层的上下文会穿透到内层的箭头函数中。

const obj = {
hello: 'world',
foo() {
// this
const bar = () => this.hello;

return bar;
}
}

window.hello = 'ES';
window.bar = obj.foo();
window.bar(); // 'world'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
程序逻辑注意事项
  箭头函数对上下文的绑定是强制性的,无法通过apply或call方法改变。

const a = {
init(){
this.bar = () => this.dam
},
dam: 'hei',
foo(){
return this.dam;
}
}

const b = {
dam: 'ha'
}

a.init();

console.log(a.foo()); // hei
console.log(a.foo.bind(b).call(a)); //ha
console.log(a.bar.call(b)); //hei
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


  不能随意在顶层作用域使用箭头函数。

// 假设当前运行环境为浏览器,则顶层上下文为“window”
const obj = {
msg: 'pong',

ping: () => this.msg // Warning!
}

obj.ping(); // undfined
var msg = 'bang!';
obj.ping(); // bang!
1
2
3
4
5
6
7
8
9
10
11
  上面代码的等价代码:

var that = this;
var obj = {
//...
ping: function(){
retuen that.msg; // Warning
}
}

// 又等价为
var that = this;
var obj = { /* ... */ };
obj.ping = function(){
return that.msg;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16


  同样地,在箭头函数中也没有arguments、 callee 甚至 caller 等对象。

const fn = () =>{
console.log(arguments);
}

fn(1, 2); // ReferenceError: arguments is not defined
//事实上输出了{ i: 0, l: false, exports: {} }
1
2
3
4
5
6
7
  若有使用 arguments 的需求,可以使用后续参数来获取参数列表。

const fn = (...args) =>{
console.log(args[0]);
}

fn(1, 2); // 1
1
2
3
4
5
6
编写语法注意事项
  在使用单行箭头函数时,请不要对单行的函数体做任何换行。
  参数列表的右括弧、箭头需要保持在同一行内。
  单行箭头函数只能包含一条语句,但如果是错误抛出语句(throw)等非表达式的语句,则需要使用花括号包裹。

const fn = x => {throw new Error('some error message')};
1
2
  若要使用单行箭头函数直接返回一个对象字面量,请使用一个括号包裹该对象字面量,而不是直接使用大括号,否则 ECMAScript 解析引擎会将其解析为一个多行箭头函数。

const ids = [1, 2, 3];
const users = ids.map(id => {id: id});
// 错误: [undefined, undefined, undefined]

const users = ids.map(id => ({id: id}));
// 正确: [{id: 1}, {id: 2}, {id: 3}]
————————————————
版权声明:本文为CSDN博主「kaelyn_X」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/kaelyn_x/article/details/78437540

posted @ 2019-09-25 13:16  鳳舞九天  阅读(408)  评论(0)    收藏  举报