1、永远不要在一个非函数代码块(if、while 等)中声明一个函数,把那个函数赋给一个变量。浏览器允许你这么做,但它们的解析表现不一致
bad:
if (currentUser) {
function test() {
console.log('Nope.');
}
}
good:
// good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
2、不要使用 arguments。可以选择 rest 语法 … 替代
使用 … 能明确你要传入的参数。另外 rest 参数是一个真正的数组,而 arguments 是一个类数组。
Bad:
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
Good:
function concatenateAll(...args) {
return args.join('');
}
3、当你必须使用函数表达式(或传递一个匿名函数)时,使用箭头函数符号
// bad
[1, 2, 3].map(function (x) {
return x * x;
});
// good
[1, 2, 3].map((x) => {
return x * x;
});
4、如果一个函数适合用一行写出并且只有一个参数,那就把花括号、圆括号和 return 都省略掉。如果不是,那就不要省略
// good
[1, 2, 3].map(x => x * x);
// good
[1, 2, 3].reduce((total, n) => {
return total + n;
}, 0);
5、总是使用 class。避免直接操作 prototype
// bad
function Queue(contents = []) {
this._queue = [...contents];
}
Queue.prototype.pop = function() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
// good
class Queue {
constructor(contents = []) {
this._queue = [...contents];
}
pop() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
}
6、不要使用 iterators,使用高阶函数例如 map() 和 reduce() 替代 for-of
const numbers = [1, 2, 3, 4, 5];
// bad
let sum = 0;
for (let num of numbers) {
sum += num;
}
sum === 15;
// good
let sum = 0;
numbers.forEach((num) => sum += num);
sum === 15;
// best (use the functional force)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;
7、使用 // FIXME: 标注问题,使用 // TODO: 标注问题的解决方式。
与React相关的规范:
1、如果模块没有状态或是没有引用refs, 推荐使用普通函数(非箭头函数)而不是类:
// bad
class Listing extends React.Component {
render() {
return <div>{this.props.hello}</div>;
}
}
// bad (relying on function name inference is discouraged)
const Listing = ({ hello }) => (
<div>{hello}</div>
);
// good
function Listing({ hello }) {
return <div>{hello}</div>;
}
2、Props 属性
避免使用数组的index来作为属性key的值,推荐使用唯一ID
// bad
{todos.map((todo, index) =>
<Todo
{...todo}
key={index}
/>
)}
// good
{todos.map(todo => (
<Todo
{...todo}
key={todo.id}
/>
))}
3、Refs
总是在Refs里使用回调函数. eslint: react/no-string-refs
// bad
<Foo ref="myRef"/>
// good
<Foo ref={ref => { this.myRef = ref; }}/>
4、函数:
// bad
class extends React.Component {
onClickDiv() {
// do stuff
}
render() {
return <div onClick={this.onClickDiv.bind(this)} />
}
}
// good
class extends React.Component {
constructor(props) {
super(props);
this.onClickDiv = this.onClickDiv.bind(this);
}
onClickDiv() {
// do stuff
}
render() {
return <div onClick={this.onClickDiv} />
}
}
网友评论