javascript箭头函数
Posted 学者先要会疑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript箭头函数相关的知识,希望对你有一定的参考价值。
原文 https://thewebjuice.com/es6-arrows/
1 使用es6箭头定义匿名函数
(msg)=>console.log(‘Hello World‘)
es5
‘use strict‘; (function (msg) { return console.log(‘Hello World‘); });
2 单个参数和多个参数
// Multiple Parameter (arg1,arg2,arg3,arg4)=>{ return arg1+arg2+arg3+arg4 } // Single Parameter (arg1)=>{ return arg1 }
es5
"use strict"; // Multiple Parameter (function (arg1, arg2, arg3, arg4) { return arg1 + arg2 + arg3 + arg4; }); // Single Parameter (function (arg1) { return arg1; });
3定义闭包
1 // Single Line Closure 2 var SayHello=(hello)=>console.log(hello) 3 4 // Multi Line Closure 5 var SayHelloAgain=(hello)=>{ 6 console.log(‘This is a multiline Closure‘) 7 console.log(hello) 8 } 9 10 // Calling the Two above Closure 11 SayHello(‘Hey I am ES6 Arrow‘) 12 SayHelloAgain(‘Heya Again!!!‘);
es5
1 ‘use strict‘; 2 3 // Single Line Closure 4 var SayHello = function SayHello(hello) { 5 return console.log(hello); 6 }; 7 8 // Multi Line Closure 9 var SayHelloAgain = function SayHelloAgain(hello) { 10 console.log(‘This is a multiline Closure‘); 11 console.log(hello); 12 }; 13 14 // Calling the Two above Closure 15 SayHello(‘Hey I am ES6 Arrow‘); 16 SayHelloAgain(‘Heya Again!!!‘);
4 Literal Syntax
1 var createObject = (x,y,color)=>({x:x,y:y,z:z})
es5
1 "use strict"; 2 3 var createObject = function createObject(x, y, color) { 4 return { x: x, y: y, z: z }; 5 };
以上是关于javascript箭头函数的主要内容,如果未能解决你的问题,请参考以下文章
如何从javascript中的一个线性箭头函数返回匿名对象? [复制]
JavaScript12_函数1:函数的参数,箭头函数的参数