您好,欢迎访问一九零五行业门户网

Javascript中编码规范的介绍(代码示例)

本篇文章给大家带来的内容是关于javascript中编码规范的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
命名规范
标准变量采用驼峰式命名
‘id’在变量名中全大写
常量全大写,用下划线连接构造函数,大写第一个字母
jquery对象必须以’$’开头命名
let thisismyname;let goodid;let reporturl;let androidversion;let iosversion;let max_count = 10;function person(name) {this.name = name;}// not goodlet body = $('body');// goodlet $body = $('body');
局部变量命名规范
s:表示字符串。例如:sname,shtml;
n:表示数字。例如:npage,ntotal;
b:表示逻辑。例如:bchecked,bhaslogin;
a:表示数组。例如:alist,agroup;
r:表示正则表达式。例如:rdomain,remail;
f:表示函数。例如:fgethtml,finit;
o:表示以上未涉及到的其他对象,例如:obutton,odate;
函数命名
小驼峰命名法,可使用常见动词约定:can 判断是否可执行某个动作,函数返回一个布尔值。true:可执行;false:不可执行
has 判断是否含有某个值, 函数返回一个布尔值。true:含有此值;false:不含有此值
is 判断是否为某个值,函数返回一个布尔值。true:为某个值;false:不为某个值
get 获取某个之,函数返回一个非布尔值
set 设置某个值,无返回值、返回是否设置成功或者返回链式对象load 加载某些数据,无返回值或者返回是否加载完成的结果
// 是否可阅读function canread() { return true;}// 获取名称function getname() { return this.name;}
引用 references
对所有的引用使用 const ;不要使用 var。
eslint: prefer-const, no-const-assign
这可以确保你无法对引用重新分配,重新分配可能会导致 bug 和难以理解的代码。// badvar a = 1;var b = 2;// goodconst a = 1;const b = 2;
如果你一定需要可变动的引用,使用 let 代替 var 。eslint: no-var jscs: disallowvar
// badvar count = 1;if (true) {count += 1;}// good, 使用 let.let count = 1;if (true) {count += 1;}
对象objects使用字面量语法创建对象。eslint: no-new-object
// badconst item = new object();// goodconst item = {};
当创建带有动态属性名称的对象时使用计算的属性名称。它们允许你在一个地方定义一个对象的所有属性。
function getkey(k) { return `a key named k`;}// badconst obj = {id: 5,name: 'san francisco',};obj[getkey('enabled')] = true;// goodconst obj = {    id: 5,    name: 'san francisco',    [getkey('enabled')]: true,};
使用对象方法速记语法。eslint: object-shorthand jscs: requireenhancedobjectliterals
// badconst atom = {value: 1,addvalue: function (value) {    return atom.value + value;  },};// goodconst atom = {value: 1,addvalue(value) {    return atom.value + value;  },};
使用对象属性速记语法。eslint: object-shorthand jscs: requireenhancedobjectliterals
const lukeskywalker = 'luke skywalker';// badconst obj = {  lukeskywalker: lukeskywalker,};// goodconst obj = {  lukeskywalker,};
将速记属性分组写在对象声明的开始处更容易看出哪些属性在使用速记语法const anakinskywalker = 'anakin skywalker';const lukeskywalker = 'luke skywalker';// badconst obj = {episodeone: 1,twojediwalkintoacantina: 2,lukeskywalker,episodethree: 3,maythefourth: 4,anakinskywalker,};// goodconst obj = {lukeskywalker,anakinskywalker,episodeone: 1,twojediwalkintoacantina: 2,episodethree: 3,maythefourth: 4,};
只用引号引无效标识符的属性。eslint: quote-props jscs: disallowquotedkeysinobjects
一般来说,我们认为比较容易阅读。它改进了语法高亮显示,并且更容易被许多js引擎优化。// badconst bad = {'foo': 3,'bar': 4,'data-blah': 5,};// goodconst good = {foo: 3,bar: 4,'data-blah': 5,};
用对象展开操作符浅复制对象,优先于object.assign 。使用对象剩余操作符来获得一个省略某些属性的新对象。// very badconst original = { a: 1, b: 2 };const copy = object.assign(original, { c: 3 }); //  `original` 是可变的 ಠ_ಠdelete copy.a; // so does this// badconst original = { a: 1, b: 2 };const copy = object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }// goodconst original = { a: 1, b: 2 };const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }const { a, ...noa } = copy; // noa => { b: 2, c: 3 }
数组 arrays使用字面量创建数组。eslint: no-array-constructor
// badconst items = new array();// goodconst items = [];
使用数组展开操作符 … 复制数组。// badconst len = items.length;const itemscopy = [];let i;for (i = 0; i < len; i += 1) {itemscopy[i] = items[i];}// goodconst itemscopy = [...items];
使用展开操作符 … 代替 array.from,来将一个类数组(array-like) 对象转换成数组。const foo = document.queryselectorall('.foo');// goodconst nodes = array.from(foo);// bestconst nodes = [...foo];
实用 array.from 代替展开操作符 … 来映射迭代,因为它避免了创建媒介数组。// badconst baz = [...foo].map(bar);// goodconst baz = array.from(foo, bar);
解构 destructuring当访问和使用对象的多个属性时,请使用对象解构。eslint: prefer-destructuring jscs: requireobjectdestructuring
// badfunction getfullname(user) { const firstname = user.firstname; const lastname = user.lastname; return `firstname lastname`;}// goodfunction getfullname(user) { const { firstname, lastname } = user; return `firstname lastname`;}// bestfunction getfullname({ firstname, lastname }) { return `firstname lastname`;}
使用数组解构。eslint: prefer-destructuring jscs: requirearraydestructuring
const arr = [1, 2, 3, 4];// badconst first = arr[0];const second = arr[1];// goodconst [first, second] = arr;
使用对象解构来实现多个返回值,而不是数组解构。jscs: disallowarraydestructuringreturn您可以随着时间的推移添加新的属性或更改排序,而不会改变调用时的位置。// badfunction processinput(input) { return [left, right, top, bottom];}// 调用者需要考虑返回数据的顺序const [left, __, top] = processinput(input);// goodfunction processinput(input) { return { left, right, top, bottom };}// 调用者只选择他们需要的数据const { left, top } = processinput(input);
字符串 strings字符串使用单引号 ‘’。eslint: quotes jscs: validatequotemarks
// badconst name = "capt. janeway";// bad - 模板字面量应该包含插值或换行符const name = `capt. janeway`;// goodconst name = 'capt. janeway';
以编程方式构建字符串时,请使用模板字符串而不是字符串连接。eslint: prefer-template template-curly-spacing jscs: requiretemplatestrings
/ badfunction sayhi(name) { return 'how are you, ' + name + '?';}// badfunction sayhi(name) { return ['how are you, ', name, '?'].join();}// badfunction sayhi(name) { return `how are you, ${ name }?`;}// goodfunction sayhi(name) { return `how are you, name?`;}
永远不要在字符串上使用 eval() ,它会打开太多的漏洞。eslint: no-eval
函数 functions使用命名函数表达式而不是函数声明。eslint: func-style jscs: disallowfunctiondeclarations
函数声明很容易被提升(hoisting),这对可读性和可维护性来说都是不利的;/ badfunction foo() { // ...}// badconst foo = function () { // ...};// good // 用明显区别于变量引用调用的词汇命名const short = function longuniquemoredescriptivelexicalfoo() { // ...};
用圆括号包裹立即调用函数表达式 (iife)。eslint: wrap-iife jscs: requireparenthesesaroundiife
一个立即调用函数表达式是一个单独的单元 – 将函数表达式包裹在括号中,后面再跟一个调用括号,这看上去很紧凑。// 立即调用函数表达式 (iife)(function () {console.log('welcome to the internet. please follow me.');}());
不要使用 arguments。可以选择 rest 语法 … 替代。使用 … 能明确你要传入的参数。另外 rest(剩余)参数是一个真正的数组,而 arguments 是一个类数组(array-like)。// badfunction concatenateall() { const args = array.prototype.slice.call(arguments); return args.join('');}// goodfunction concatenateall(...args) { return args.join('');}
使用默认参数语法,而不要使用一个变化的函数参数// really badfunction handlethings(opts) { // 更加糟糕: 如果参数 opts 是 falsy(假值) 的话,它将被设置为一个对象, // 这可能是你想要的,但它可以引起一些小的错误。 opts = opts || {}; // ...}// still badfunction handlethings(opts) { if (opts === void 0) { opts = {};}// ...}// goodfunction handlethings(opts = {}) { // ...}
始终将默认参数放在最后。// badfunction handlethings(opts = {}, name) {// ...}// goodfunction handlethings(name, opts = {}) {// ...}
隔开函数签名,括号两边用空格隔开。// badconst f = function(){};const g = function (){};const h = function() {};// goodconst x = function () {};const y = function a() {};
不要改变参数。eslint: no-param-reassign
操作作为参数传入的对象,可能会在调用原始对象时造成不必要的变量副作用。(对象是引用类型)// badfunction f1(obj) {obj.key = 1;}// goodfunction f2(obj) { const key = object.prototype.hasownproperty.call(obj, 'key') ? obj.key : 1;}
箭头函数 arrow functions当您必须使用匿名函数(如在传递一个内联回调时),请使用箭头函数表示法。eslint: prefer-arrow-callback, arrow-spacing jscs: requirearrowfunctions
它创建了一个在 this 上下文中执行的函数的版本,这通常是你想要的,而且这样的写法更为简洁。// bad[1, 2, 3].map(function (x) { const y = x + 1; return x * y;});// bad[1, 2, 3].map( _ => {    return 0;});// good[1, 2, 3].map((x) => {  const y = x + 1;  return x * y;});// good[1, 2, 3].map(() => {    return 0;});
如果函数体由一个返回无副作用(side effect)的expression(表达式)的单行语句组成,那么可以省略大括号并使用隐式返回。否则,保留大括号并使用 return 语句。// bad[1, 2, 3].map(number => {const nextnumber = number + 1;return `a string containing the nextnumber.`;});// good[1, 2, 3].map(number => `a string containing the number.`);
如果表达式跨多行,将其包裹在括号中,可以提高可读性。// bad['get', 'post', 'put'].map(httpmethod => object.prototype.hasownproperty.call(  httpmagicobjectwithaverylongname,  httpmethod,  ));// good['get', 'post', 'put'].map(httpmethod => (  object.prototype.hasownproperty.call(  httpmagicobjectwithaverylongname,  httpmethod,  )));
如果你的函数只有一个参数并且不使用大括号,则可以省略参数括号。否则,为了清晰和一致性,总是给参数加上括号。// bad[1, 2, 3].map((x) => x * x);// good[1, 2, 3].map(x => x * x);// good[1, 2, 3].map(number => (`a long string with the number. it’s so long that we don’t want it to take up space on the .map line!`));// 总是添加()// bad[1, 2, 3].map(x => {  const y = x + 1;  return x * y;});// good[1, 2, 3].map((x) => {  const y = x + 1;  return x * y;});
避免使用比较运算符(< =, >=)时,混淆箭头函数语法(=>)。// badconst itemheight = item => item.height > 256 ? item.largesize : item.smallsize;// badconst itemheight = (item) => item.height > 256 ? item.largesize : item.smallsize;// goodconst itemheight = item => (item.height > 256 ? item.largesize : item.smallsize);// goodconst itemheight = (item) => {  const { height, largesize, smallsize } = item;  return height > 256 ? largesize : smallsize;};
类 classes & 构造函数 constructors总是使用 *class。避免直接操作 prototype 。// badfunction queue(contents = []) {  this.queue = [...contents];}queue.prototype.pop = function () {  const value = this.queue[0];  this.queue.splice(0, 1);  return value;};// goodclass queue {  constructor(contents = []) {    this.queue = [...contents];  }  pop() {    const value = this.queue[0];    this.queue.splice(0, 1);    return value;  }}
使用 extends 继承。因为 extends 是一个内置的原型继承方法并且不会破坏 instanceof。// badconst inherits = require('inherits');  function peekablequeue(contents) {  queue.apply(this, contents);}inherits(peekablequeue, queue);  peekablequeue.prototype.peek = function () {  return this.queue[0];};// goodclass peekablequeue extends queue {  peek() {    return this.queue[0];  }}
如果没有指定,类有一个默认的构造函数。一个空的构造函数或者只是委托给父类则不是必须的。eslint: no-useless-constructor
// badclass jedi {  constructor() {}  getname() {    return this.name;  }}// badclass rey extends jedi {  constructor(...args) {    super(...args);  }}// goodclass rey extends jedi {  constructor(...args) {    super(...args);    this.name = 'rey';  }}
避免重复类成员。eslint: no-dupe-class-members
// badclass foo {  bar() { return 1; }  bar() { return 2; }}// goodclass foo {  bar() { return 1; }}// goodclass foo {  bar() { return 2; }}
模块 modules总是使用模块 (import/export) 而不是其他非标准模块系统。// badconst airbnbstyleguide = require('./airbnbstyleguide');module.exports = airbnbstyleguide.es6;// okimport airbnbstyleguide from './airbnbstyleguide';export default airbnbstyleguide.es6;// bestimport { es6 } from './airbnbstyleguide';export default es6;
不要使用通配符 import(导入)。这样能确保你只有一个默认 export(导出)。// badimport * as airbnbstyleguide from './airbnbstyleguide';// goodimport airbnbstyleguide from './airbnbstyleguide';
不要从 import(导入) 中直接 export(导出)。虽然一行代码简洁明了,但有一个明确的 import(导入) 方法和一个明确的 export(导出) 方法,使事情能保持一致。// bad// filename es6.jsexport { es6 as default } from './airbnbstyleguide';// good// filename es6.jsimport { es6 } from './airbnbstyleguide';export default es6;
一个地方只在一个路径中 import(导入) 。// badimport foo from 'foo';// … 其他一些 imports … //import { named1, named2 } from 'foo';// goodimport foo, { named1, named2 } from 'foo';// goodimport foo, {  named1,  named2,} from 'foo';
不要 export(导出) 可变绑定。eslint: import/no-mutable-exports
一般应该避免可变性,特别是在导出可变绑定时。虽然一些特殊情况下,可能需要这种技术,但是一般而言,只应该导出常量引用。// badlet foo = 3;export { foo };// goodconst foo = 3;export { foo };
在只有单个导出的模块中,默认 export(导出) 优于命名 export(导出)。eslint: import/prefer-default-export
为了鼓励更多的文件只有一个 export(导出),这有利于模块的可读性和可维护性。// badexport function foo() {}// goodexport default function foo() {}
将所有 import 导入放在非导入语句的上面。eslint: import/first
由于 import 被提升,保持他们在顶部,防止意外的行为。// badimport foo from 'foo';foo.init();import bar from 'bar';// goodimport foo from 'foo';import bar from 'bar';foo.init();
多行导入应该像多行数组和对象字面量一样进行缩进。// badimport {longnamea, longnameb, longnamec, longnamed, longnamee} from 'path';// goodimport {longnamea,longnameb,longnamec,longnamed,longnamee,} from 'path';
属性 properties使用 点语法(.) 来访问对象的属性。eslint: dot-notation jscs: requiredotnotation
const luke = {jedi: true,age: 28,};// badconst isjedi = luke['jedi'];// goodconst isjedi = luke.jedi;
当通过变量访问属性时使用中括号 []。const luke = {jedi: true,age: 28,};function getprop(prop) {return luke[prop];}const isjedi = getprop('jedi');
求幂时使用求幂运算符 ** 。eslint: no-restricted-properties.
// badconst binary = math.pow(2, 10);// goodconst binary = 2 ** 10;
变量 variables总是使用 const 或 let 来声明变量。 不这样做会导致产生全局变量。 我们希望避免污染全局命名空间。eslint: no-undef prefer-const
// badsuperpower = new superpower();// goodconst superpower = new superpower();
将所有的 const 和 let 分组 。当你需要把已分配的变量分配给一个变量时非常有用// badlet i, len, dragonball,items = getitems(),gosportsteam = true;// badlet i;const items = getitems();let dragonball;const gosportsteam = true;let len;// goodconst gosportsteam = true;const items = getitems();let dragonball;let i;let length;
变量不要链式赋值。eslint: no-multi-assign
链接变量赋值会创建隐式全局变量。// bad(function example() {// javascript 将其解析为// let a = ( b = ( c = 1 ) );// let关键字只适用于变量a;// 变量b和c变成了全局变量。let a = b = c = 1;}());console.log(a); // 抛出 referenceerror(引用错误)console.log(b); // 1console.log(c); // 1// good(function example() {let a = 1;let b = a;let c = a;}());console.log(a); // 抛出 referenceerror(引用错误)console.log(b); // 抛出 referenceerror(引用错误)console.log(c); // 抛出 referenceerror(引用错误)// 同样适用于 `const`
避免使用一元递增和递减运算符(++, –)。根据 eslint 文档,一元递增和递减语句会受到自动插入分号的影响,并可能导致应用程序中的值递增或递减,从而导致无提示错误。使用像 num += 1 而不是 num++ 或 num ++ 这样的语句来改变你的值也更具有表现力。不允许一元递增和递减语句也会阻止您无意中预先递增/递减值,这也会导致程序中的意外行为。// badconst array = [1, 2, 3];let num = 1;num++;--num;let sum = 0;let truthycount = 0;for (let i = 0; i < array.length; i++) { let value = array[i]; sum += value; if (value) { truthycount++; } }// good const array = [1, 2, 3]; let num = 1; num += 1; num -= 1; const sum = array.reduce((a, b) => a + b, 0);const truthycount = array.filter(boolean).length;
比较运算符 comparison operators 和 等号 equality使用 === 和 !== 优先于 == 和 !=。eslint: eqeqeq
对于布尔值使用简写,但对于字符串和数字使用显式比较。// badif (isvalid === true) {// ...}// goodif (isvalid) {// ...}// badif (name) {// ...}// goodif (name !== '') {// ...}// badif (collection.length) {// ...}// goodif (collection.length > 0) {// ...}
在 case 和 default 子句中,使用大括号来创建包含词法声明的语句块(例如 let, const, function, 和 class).eslint: no-case-declarations
// badswitch (foo) {  case 1:    let x = 1;  break;  case 2:    const y = 2;  break;  case 3:    function f() {      // ...    }  break;default:  class c {}}// goodswitch (foo) {  case 1: {    let x = 1;    break;  }  case 2: {    const y = 2;    break;  }  case 3: {    function f() {      // ...    }    break;  }  case 4:    bar();    break;  default: {    class c {}  }}
三元表达式不应该嵌套,通常写成单行表达式。eslint: no-nested-ternary
// badconst foo = maybe1 > maybe2? bar: value1 > value2 ? baz : null;// 拆分成2个分离的三元表达式const maybenull = value1 > value2 ? 'baz' : null;// betterconst foo = maybe1 > maybe2? 'bar': maybenull;// bestconst foo = maybe1 > maybe2 ? 'bar' : maybenull;
避免不必要的三元表达式语句。eslint: no-unneeded-ternary
/ badconst foo = a ? a : b;const bar = c ? true : false;const baz = c ? false : true;// goodconst foo = a || b;const bar = !!c;const baz = !c;
当运算符混合在一个语句中时,请将其放在括号内。混合算术运算符时,不要将 * 和 % 与 + , -,,/ 混合在一起。eslint: no-mixed-operators
这可以提高可读性,并清晰展现开发者的意图。/ badconst foo = a && b < 0 || c > 0 || d + 1 === 0;// badconst bar = a ** b - 5 % d;// badif (a || b && c) {return d;}// goodconst foo = (a && b < 0) || c > 0 || (d + 1 === 0);// goodconst bar = (a ** b) - (5 % d);// goodif ((a || b) && c) {return d;}// goodconst bar = a + b / c * d;
代码块 blocks使用大括号包裹所有的多行代码块。eslint: nonblock-statement-body-position
// badif (test)  return false;// goodif (test) return false;// goodif (test) {  return false;}// badfunction foo() { return false; }// goodfunction bar() {  return false;}
如果通过 if 和 else 使用多行代码块,把 else 放在 if 代码块闭合括号的同一行。eslint: brace-style
// badif (test) {  thing1();  thing2();}else {  thing3();}// goodif (test) {  thing1();  thing2();} else {  thing3();}
如果一个 if 块总是执行一个 return 语句,后面的 else 块是不必要的。在 else if 块中的 return,可以分成多个 if 块来 return 。eslint: no-else-return
// badfunction foo() {  if (x) {    return x;  } else {    return y;  }}// badfunction cats() {  if (x) {    return x;  } else if (y) {    return y;  }}// badfunction dogs() {  if (x) {    return x;  } else {  if (y) {    return y;  }}}// goodfunction foo() {  if (x) {    return x;  }return y;}// goodfunction cats() {  if (x) {    return x;  }  if (y) {    return y;  }}//goodfunction dogs(x) {  if (x) {    if (z) {      return y;  }} else {  return z;  }}
控制语句 control statements如果您的控制语句(if, while 的)太长或超过最大行长度,那么每个(分组)条件可以放单独一行。逻辑运算符应该放在每行起始处。// badif ((foo === 123 || bar === 'abc') && doesitlookgoodwhenitbecomesthatlong() && isthisreallyhappening()) { thing1();}// badif (foo === 123 &&  bar === 'abc') {  thing1();}// badif (foo === 123  && bar === 'abc') {  thing1();}// badif (  foo === 123 &&  bar === 'abc') {  thing1();}// goodif (  foo === 123  && bar === 'abc') {  thing1();}// goodif (  (foo === 123 || bar === abc)  && doesitlookgoodwhenitbecomesthatlong()  && isthisreallyhappening()) {  thing1();}// goodif (foo === 123 && bar === 'abc') {  thing1();}
注释 comments多行注释使用 /* … /。/*** @param {grid} grid 需要合并的grid* @param {array} cols 需要合并列的index(序号)数组;从0开始计数,序号也包含。* @param {boolean} isallsome 是否2个tr的cols必须完成一样才能进行合并。true:完成一样;false(默认):不完全一样* @return void* @author 单志永 2018/11/8*/function mergecells(grid, cols, isallsome) {    // do something}
单行注释使用 // 。将单行注释放在续注释的语句上方。在注释之前放置一个空行,除非它位于代码块的第一行。// badconst active = true;  // is current tab// good// is current tabconst active = true;// badfunction gettype() {  console.log('fetching type...');  // set the default type to 'no type'  const type = this.type || 'no type';  return type;}// goodfunction gettype() {  console.log('fetching type...');  // set the default type to 'no type'  const type = this.type || 'no type';  return type;}// also goodfunction gettype() {  // set the default type to 'no type'  const type = this.type || 'no type';  return type;}
所有注释符和注释内容用一个空格隔开,让它更容易阅读。eslint: spaced-comment
// bad//is current tabconst active = true;// good// is current tabconst active = true;// bad/***make() returns a new element*based on the passed-in tag name*/function make(tag) {// ...return element;}// good/*** make() returns a new element* based on the passed-in tag name*/function make(tag) {// ...return element;}
给注释增加 fixme 或 todo 的前缀,可以帮助其他开发者快速了解这个是否是一个需要重新复查的问题,或是你正在为需要解决的问题提出解决方案。这将有别于常规注释,因为它们是可操作的。使用 fixme – need to figure this out 或者 todo – need to implement。使用 // fixme: 来标识需要修正的问题。注:如果代码中有该标识,说明标识处代码需要修正,甚至代码是错误的,不能工作,需要修复,如何修正会在说明中简略说明。lass calculator extends abacus {  constructor() {    super();    // fixme: shouldn’t use a global here    total = 0;  }}
使用 // todo: 来标识需要实现的问题。注:如果代码中有该标识,说明在标识处有功能代码待编写,待实现的功能在说明中会简略说明。class calculator extends abacus {  constructor() {    super();    // todo: total should be configurable by an options param    this.total = 0;  }}
空格 whitespace使用 2 个空格作为缩进// badfunction foo() {∙∙∙∙let name;}// badfunction bar() {∙let name;}// goodfunction baz() {∙∙let name;}
在大括号前放置 1 个空格。eslint: space-before-blocks jscs: requirespacebeforeblockstatements
// badfunction test(){  console.log('test');}// goodfunction test() {  console.log('test');}// baddog.set('attr',{  age: '1 year',  breed: 'bernese mountain dog',});// gooddog.set('attr', {  age: '1 year',  breed: 'bernese mountain dog',});
在控制语句(if、while 等)的小括号前放一个空格。在函数调用及声明中,不在函数的参数列表前加空格。eslint: keyword-spacing jscs: requirespaceafterkeywords
// badif(isjedi) {  fight ();}// goodif (isjedi) {  fight();}// badfunction fight () {  console.log ('swooosh!');}// goodfunction fight() {  console.log('swooosh!');}
使用空格把运算符隔开。eslint: space-infix-ops jscs: requirespacebeforebinaryoperators, requirespaceafterbinaryoperators
// badconst x=y+5;// goodconst x = y + 5;
在文件末尾插入一个空行。eslint: eol-last
// badimport { es6 } from './airbnbstyleguide';// ...export default es6;// badimport { es6 } from './airbnbstyleguide';// ...export default es6;// goodimport { es6 } from './airbnbstyleguide';// ...export default es6;
长方法链式调用时使用缩进(2个以上的方法链式调用)。使用一个点 . 开头,强调该行是一个方法调用,不是一个新的声明。eslint: newline-per-chained-call no-whitespace-before-property
// bad$('#items').find('.selected').highlight().end().find('.open').updatecount();// bad$('#items').find('.selected').highlight().end().find('.open').updatecount();// good$('#items').find('.selected').highlight().end().find('.open').updatecount();// badconst leds = stage.selectall('.led').data(data).enter().append('svg:svg').classed('led', true).attr('width', (radius + margin) * 2).append('svg:g').attr('transform', `translate(${radius + margin},${radius + margin})`).call(tron.led);// goodconst leds = stage.selectall('.led').data(data).enter().append('svg:svg').classed('led', true).attr('width', (radius + margin) * 2).append('svg:g').attr('transform', `translate(${radius + margin},${radius + margin})`).call(tron.led);// goodconst leds = stage.selectall('.led').data(data);
不要在圆括号内加空格。// badfunction bar( foo ) {  return foo;}// goodfunction bar(foo) {  return foo;}// badif ( foo ) {  console.log(foo);}// goodif (foo) {  console.log(foo);}
不要在中括号内添加空格。eslint: array-bracket-spacing jscs: disallowspacesinsidearraybrackets
// badconst foo = [ 1, 2, 3 ];console.log(foo[ 0 ]);// goodconst foo = [1, 2, 3];console.log(foo[0]);
在大括号内添加空格// badconst foo = {clark: 'kent'};// goodconst foo = { clark: 'kent' };
类型转换 type casting & coercion在声明语句的开始处就执行强制类型转换.字符串:eslint: no-new-wrappers
// => this.reviewscore = 9;// badconst totalscore = new string(this.reviewscore); // typeof totalscore 是 object 而不是 string// badconst totalscore = this.reviewscore + ''; // 调用 this.reviewscore.valueof()// badconst totalscore = this.reviewscore.tostring(); // 不能保证返回一个字符串// goodconst totalscore = string(this.reviewscore);
使数字: 使用 number 进行转换,而 parseint 则始终以基数解析字串。eslint: radix no-new-wrappers
const inputvalue = '4';// badconst val = new number(inputvalue);// badconst val = +inputvalue;// badconst val = inputvalue >> 0;// badconst val = parseint(inputvalue);// goodconst val = number(inputvalue);// goodconst val = parseint(inputvalue, 10);
布尔值:eslint: no-new-wrappers
const age = 0;// badconst hasage = new boolean(age);// goodconst hasage = boolean(age);// bestconst hasage = !!age;
命名规则 naming conventions避免使用单字母名称。使你的命名具有描述性。eslint: id-length
// badfunction q() {// ...}// goodfunction query() {// ...}
当命名对象,函数和实例时使用驼峰式命名。eslint: camelcase jscs: requirecamelcaseoruppercaseidentifiers
// badconst objecttsssss = {};const this_is_my_object = {};function c() {}// goodconst thisismyobject = {};function thisismyfunction() {}
当命名构造函数或类的时候使用 pascalcase 式命名,(注:即单词首字母大写)。eslint: new-cap
// badfunction user(options) {  this.name = options.name;}const bad = new user({  name: 'nope',});// goodclass user {  constructor(options) {    this.name = options.name;  }}const good = new user({  name: 'yup',});
当 导出(export) 一个默认函数时使用驼峰式命名。你的文件名应该和你的函数的名字一致。function makestyleguide() {// ...}export default makestyleguide;
当导出一个 构造函数 / 类 / 单例 / 函数库 / 纯对象时使用 pascalcase 式命名,(愚人码头注:即单词首字母大写)。const airbnbstyleguide = {  es6: {    },};export default airbnbstyleguide;
存取器 accessors
属性的存取器函数不是必须的。
別使用 javascript 的 getters/setters,因为它们会导致意想不到的副作用,而且很难测试,维护和理解。相反,如果要使用存取器函数,使用 getval() 及 setval(‘hello’)。
// badclass dragon {  get age() {    // ...  }  set age(value) {    // ...  }}// goodclass dragon {  getage() {    // ...  }  setage(value) {    // ...  }}
如果属性/方法是一个 boolean, 使用 isval() 或 hasval() 方法。// badif (!dragon.age()) {  return false;}// goodif (!dragon.hasage()) {  return false;})
以上就是javascript中编码规范的介绍(代码示例)的详细内容。
其它类似信息

推荐信息