ES2015新增的特性箭头表达式,省去了关键词function,文中``双撇号和${}是Typescript的语法。以下是一些学习笔记:
1.单行箭头表达式:
1 var foo = (arg1,arg2) => arg1 + arg2; 2 //上述表达式相当于 3 var foo = function (arg1, arg2) { return arg1 + arg2; };
2.多行箭头表达式(必须使用{}大括号):
1 var foo = (arg1, agr2) => { 2 return arg1 + agr2; 3 } 4 5 //以上表达式相当于 6 var foo = function (arg1, arg2) { 7 return arg1 + arg2; 8 };
3.无参数:
1 var foo = () => {} 2 3 //以上表达式相当于 4 var foo = function () {}
4.一个参数(无需使用()小括号):
1 var foo = arg => { 2 return arg*arg; 3 } 4 5 //以上表达式相当于 6 var foo = function (arg) { 7 return arg*arg; 8 }
5.栗子:
1 var arr = [1,2,3,4,5]; 2 console.log(arr.filter(value => value%2 == 0)) 3 4 //以上代码相当于 5 var arr = [1, 2, 3, 4, 5]; 6 console.log(arr.filter(function (value) { return value % 2 == 0; })); //[2,4]返回被2整除的值
6.箭头表达式中的this关键字:
//(1)ES5方式(计时器中无法找到this)
1 function Foo (name:string) { 2 this.name = name; 3 setInterval(function () { 4 console.log(`name is: ${this.name}`); 5 },1000); 6 } 7 var foo = new Foo('莎士比亚'); 8 //返回name is---无法找到this.name
//(2)ES6方式(计时器中可以找到this)
1 function Foo (name:string) { 2 this.name = name; 3 setInterval(() => { 4 console.log(`name is: ${this.name}`); 5 },1000); 6 } 7 var foo = new Foo("莎士比亚"); 8 9 //name is: 莎士比亚