Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

箭头函数的参数是否加括号? #14

Open
YanagiEiichi opened this issue Nov 3, 2015 · 9 comments
Open

箭头函数的参数是否加括号? #14

YanagiEiichi opened this issue Nov 3, 2015 · 9 comments

Comments

@YanagiEiichi
Copy link
Contributor

@furybean @CarterLi 喷子龙,喷子李,你们怎么看?

callback((item) => {});

vs

callback(item => {});

@ElemeFE/owner


是否加括号
总是加
只有一个时不加 👍 👍
@iqingting
Copy link
Contributor

一个参数不加

@CarterLi
Copy link
Contributor

CarterLi commented Nov 3, 2015

一个参数不加

另外还有

callback(item => {
  return {};
});

vs

callback(item => ({}));

@YanagiEiichi
Copy link
Contributor Author

👍 尽量直接使用表达式,因为可以省去一个 return。

@CarterLi
Copy link
Contributor

CarterLi commented Nov 3, 2015

@YanagiEiichi 不能完全不加吧,所以只有“总是加”和“只有一个时不加”两个选项

() => x
x => x
(a, b) => a + b

但是因为“只有一个参数”的callback非常常用,所以单独拎出来

另外没有参数时个人习惯写

()=> x // 右括号与等号间无空格

而非

() => x // 右括号与等号间有空格

有参数时都加空格

@YanagiEiichi
Copy link
Contributor Author

主要是存在解构时必须加,比如

xxx.then(({ userId, userName }) => {
  // do something
});

然而它只有一个参数。。

@CarterLi
Copy link
Contributor

CarterLi commented Nov 3, 2015

另外标准规定,箭头函数不能作为构造函数使用(不能用 new 操作符),所以某些写法其实是错误的
例如

oneModule.controller('name', $scope => XXX)

然而 angular 中 controller 都是作为构造函数被 new 出来的
如果不经过 babel 翻译,就会出现 $scope => XXX is not a constructorTypeError

相对的,classconstructor 成员函数必须使用 new 调用

@CarterLi
Copy link
Contributor

CarterLi commented Nov 3, 2015

题外话,建议推广一下 controllerAs 的写法,然后我们就可以写

module.controller('name', class NameCtrl {
  constructor() {}
  action1() {}
  action2() {}
});

然后

<div ng-controller="NameCtrl as name">
  <button ng-click="name.action1()">Action</button>
</div>

PS: 虽然还是 proposal,这个可以有:https://github.com/jeffmo/es-class-static-properties-and-fields

@YanagiEiichi
Copy link
Contributor Author

确实,controller 应该是 class

@YanagiEiichi
Copy link
Contributor Author

controller as 的写法就算了,我不推荐自己去写 ng-controller,controller 全部交给路由,其它需求交给 directive(directive 也应该是 class)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants