ecomfe / es6-code-style

Discuss & record
1 stars 0 forks source link

arrow functions #7

Open otakustay opened 9 years ago

otakustay commented 9 years ago

函数语法选择

箭头函数的特点是:

  1. 语法简单
  2. 固定this
  3. babel编译后性能会较低(因为固定this)

建议如下:

  1. 在模块作用域(顶级作用域)的函数都使用function foo() {},不要用箭头函数,这里用不了this
  2. 如果需要变thisthis不是当前词法this的,使用function foo() {},典型的就是声明一个property descriptor里的getsetthis是依赖执行时给定的。不过尽量避免变this的函数出现
  3. 需要递归的用function foo() {},别蛋疼用去Y因子做这事,你不累看的人累
  4. 对象直接量和类里面能用方法语法就用
  5. 其它情况能用箭头就用箭头
  6. 需要绑定词法this的一概用箭头,甚至可以不用bind

    箭头函数

参数一定要用括号,哪怕只有一个参数

只有一个语句的函数不换行不写return不加大括号

ajax(url).then((result) => console.log(result));
array.map((item) => item.name);

避免多个箭头函数嵌套,看得眼疼

otakustay commented 9 years ago

http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6

otakustay commented 9 years ago

说下我的建议:

  1. 全局下用function
  2. 一个模块定义一个普通对象(命名空间),其下的函数用function
  3. class里用标准方法语法
  4. 不需要绑this的对象字面量里的函数用标准方法语法
  5. 其它一切可能的情况用箭头
  6. 箭头不行的时候用function