编程规范

来源:互联网 发布:网络营销策划书例文 编辑:程序博客网 时间:2024/06/18 08:25
  • let仅在块级作用域里面有效,var可能成为全局变量;var变量提升,未声明即可以使用,let不可以变量提升。
  • 全局环境中应该优先选用const,符合函数编程思想。
  • 静态字符串一律使用单引号或反引号,不使用双引号。动态字符串使用反引号。
const a = 'foobar';const b = `foo${a}bar`;
  • 使用数组成员对变量赋值时,优先使用解构赋值。函数的参数如果是对象的成员,优先使用解构赋值。如果函数返回多个值,优先使用对象的解构赋值,而不是数组的解构赋值。这样便于以后添加返回值,以及更改返回值的顺序。
//数组解构赋值 case1const arr = [1, 2, 3, 4];const [first, second] = arr;// good  函数参数解构赋值 case2 function getFullName(obj) {  const { firstName, lastName } = obj;}// bestfunction getFullName({ firstName, lastName }) {}// good  函数返回值解构赋值 case3function processInput(input) {  return { left, right, top, bottom };}const { left, right } = processInput(input);
  • 单行定义的对象,最后一个成员不以逗号结尾。多行定义的对象,最后一个成员以逗号结尾。
const a = { k1: v1, k2: v2 };const b = {  k1: v1,  k2: v2,};
  • 对象尽量静态化,一旦定义,就不得随意添加新的属性。如果添加属性不可避免,要使用Object.assign方法。
// 此法添加属性const a = {};Object.assign(a, { x: 3 });
  • 如果对象的属性名是动态的,可以在创造对象的时候,使用属性表达式定义。
const obj = {  id: 5,  name: 'San Francisco',  [getKey('enabled')]: true, //属性名为动态,使用属性表达式};
  • 对象的属性和方法,尽量采用简洁表达法,这样易于描述和书写。
var ref = 'some value';// badconst atom = {  ref: ref,  value: 1,  addValue: function (value) {    return atom.value + value;  },};// goodconst atom = {  ref,  value: 1,  addValue(value) {    return atom.value + value;  },};
  • 优先使用扩展运算符(…)拷贝数组。此法简明。使用Array.from方法,将类似数组的对象转为数组。
const itemsCopy = [...items];const foo = document.querySelectorAll('.foo');const nodes = Array.from(foo);
  • 函数最好写成箭头形式的函数,因为这样更简洁,并且绑定了this。特别是立即执行函数。
// good[1, 2, 3].map((x) => {  return x * x;});// best[1, 2, 3].map(x => x * x);(() => {  console.log('Welcome to the Internet.');})();
  • 简单的、单行的、不会复用的函数,建议采用箭头函数。如果函数体较为复杂,行数较多,还是应该采用传统的函数写法。
  • 不要在函数体内使用arguments变量,使用rest运算符(…)代替。因为rest运算符显式表明你想要获取参数,而且arguments是一个类似数组的对象,而rest运算符可以提供一个真正的数组。
// badfunction concatenateAll() {  const args = Array.prototype.slice.call(arguments);  return args.join('');}// goodfunction concatenateAll(...args) {  return args.join('');}
  • 使用默认值语法设置函数参数的默认值。
function handleThings(opts = {}) {  // ...}
  • 注意区分Object和Map,只有模拟实体对象时,才使用Object。如果只是需要key: value的数据结构,使用Map结构。因为Map有内建的遍历机制。
let map = new Map(arr);for (let item of map.entries()) {  console.log(item[0], item[1]);}
  • 总是用Class,取代需要prototype的操作。因为Class的写法更简洁,更易于理解。使用extends实现继承,因为这样更简单,不会有破坏instanceof运算的危险。
class Queue {  constructor(contents = []) {    this._queue = [...contents];  }  pop() {    const value = this._queue[0];    this._queue.splice(0, 1);    return value;  }}class PeekableQueue extends Queue {  peek() {    return this._queue[0];  }}
0 0
原创粉丝点击