程序员

JavaScript编程规范

2018-07-06  本文已影响11人  前端小兵

1. 声明(块级作用域)

(1)let取代var

'use strict';

if (true) {
  let x = 'hello';
}

for (let i = 0; i < 10; i++) {
  console.log(i);
}
'use strict';

if (true) {
  console.log(x); // ReferenceError
  let x = 'hello';
}

(2)全局常量和线程安全

2. 字符串

// bad
const a = 'foobar';
const b = 'foo' + a + 'bar';

// acceptable
const c = `foobar`

// good
const a = 'foobar';
const b = `foo${a}bar`;
const c = `foobar`;

3. 结构赋值

const arr = [1, 2, 3, 4, 5];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;
// bad 
function getFullName(user) {
    const firstName = user.firstName;
    const lastName = user.lastName;
}

// good
function getFullName(obj) {
    const { firstName, lastName } = obj;
}

// best
function getFullName({firstName,lastName}) {
    
}

4. 对象

// bed
const a = { k1: v1, k2: v2,};
const b = {
    k1: v1,
    k2:v2
}

// good
const a = { k1: v1, k2: v2 };
const b = {
    k1: v1,
    k2: v2,
}
// bad
const a = {};
a.x = 3;

// if reshape unavoidable
const a = {};
Object.assign(a, {x: 2});

// good
const a = {x: null};
a.x = 3;
let ref = 'some value';

// bad
const atom = {
    ref: ref,
    value: 1,
    addValue: function (value) {
        return atom.value + vlaue
    },
};

// good
const atom = {
    ref,
    
    value: 1,
    
    addValue(value) {
        return atom.value + value
    }
}

5. 数组

// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];
const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);

6. 函数

(() => {
    console.log('Welcome to the Internet.')
})();
// bad
[1, 2, 3].map(function (x) {
  return x * x;  
});

// good
[1, 2, 3].map((x) => {
    return x * x;
});

// best
[1, 2, 3].map(x => x*x);
// bad
const self = this;
const boundMethod = function(..params) {
    return method.apply(self,params);
}

// acceptable
const boundMethod = method.bind(this);

// best
const boundMethod = (...params) => method.apply(this, params);
// bad
function divide(a, b, option = false ) {
}

// good
function divide(a, b, { option = false } = {}) {
}
// bad
function concatenateAll() {
  const args = Array.prototype.slice.call(arguments);
  return args.join('');
}

// good
function concatenateAll(...args) {
  return args.join('');
}
// bad
function handleThings(opts) {
  opts = opts || {};
}

// good
function handleThings(opts = {}) {
  // ...
}

7. Map 结构

let map = new Map(arr);
for (let key of map.keys()) {
    console.log(key);
}
for (let value of map.values()) {
    console.log(value);
}
for (let item of map.entries()) {
    console.log(item[0],itme[1])
}

8. Class

// 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;
  }
}
// bad
const inherits = require('inherits');
function PeekableQueue(contents) {
  Queue.apply(this, contents);
}
inherits(PeekableQueue, Queue);
PeekableQueue.prototype.peek = function() {
  return this._queue[0];
}

// good
class PeekableQueue extends Queue {
  peek() {
    return this._queue[0];
  }
}

9. 模块

// bad
const moduleA = require('moduleA');
const func1 = moduleA.func1;
const func2 = moduleA.func2;

// good
import { func1, func2 } from 'moduleA';
// commonJS的写法
var React = require('react');

var Breadcrumbs = React.createClass({
  render() {
    return <nav />;
  }
});

module.exports = Breadcrumbs;

// ES6的写法
import React from 'react';

class Breadcrumbs extends React.Component {
  render() {
    return <nav />;
  }
};

export default Breadcrumbs;
// bad
import * as myObject from './importModule';

// good
import myObject from './importModule';
function makeStyleGuide() {
}

export default makeStyleGuide;- ESLint 是一个语法规则和代码风格的检查工具,可以用来保证写出语法正确、风格统一的代码。
const StyleGuide = {
  es6: {
  }
};

export default StyleGuide;
上一篇 下一篇

猜你喜欢

热点阅读