javascript 规范

本章节参考ESlint规范,为大家介绍下书写js的标准规范。以下标准只是一种参考和推荐,并不代表该写法是效率最高、最好的,只是希望大家能够按照一定的标准开发,是的开发出来的代码更加规范、美观。

使用单引号

eslint: quotes

console.log('hello there')
$("<div class='box'>")

不要使用无用变量

eslint: no-unused-vars

function myFunction () {
  var result = something()   // ✗ avoid 
}

在if和for等关键字和括号前,增加一个空格

eslint: keyword-spacing

if (condition) { ... }   // ✓ ok 
if(condition) { ... }    // ✗ avoid

在方程的参数变量声明前加空格

eslint: space-before-function-paren

function name (arg) { ... }   // ✓ ok 
function name(arg) { ... }    // ✗ avoid 

run(function () { ... })      // ✓ ok 
run(function() { ... })       // ✗ avoid

始终使用 === , 而不是 ==.

例外: obj == null 允许使用,在用于检查 null || undefined.

eslint: eqeqeq

if (name === 'John') // ✓ ok if (name == 'John') // ✗ avoid if (name !== 'John') // ✓ ok if (name != 'John') // ✗ avoid

单目运算符前、后加入空格

eslint: space-infix-ops

// ✓ ok 
var x = 2
var message = 'hello, ' + name + '!'
// ✗ avoid 
var x=2
var message = 'hello, '+name+'!'

在逗号后面,必须增加一个空格

eslint: comma-spacing

// ✓ ok 
var list = [1, 2, 3, 4]
function greet (name, options) { ... }
// ✗ avoid 
var list = [1,2,3,4]
function greet (name,options) { ... }

保持else与}和{在同一行,并且前后增加括号

eslint: brace-style

// ✓ ok 
if (condition) {
  // ... 
} else {
  // ... 
}
// ✗ avoid 
if (condition) {
  // ... 
}
else {
  // ... 
}

多行语句指令必须用{}包裹

eslint: curly

// ✓ ok 
if (options.quiet !== true) console.log('done')
// ✓ ok 
if (options.quiet !== true) {
  console.log('done')
}
// ✗ avoid 
if (options.quiet !== true)
  console.log('done')

始终要处理异常函数变量

eslint: handle-callback-err

// ✓ ok 
run(function (err) {
  if (err) throw err
  window.alert('done')
})
// ✗ avoid 
run(function (err) {
  window.alert('done')
})

 在执行全局指令时,始终增加全局变量window

例外: document, console 和 navigator

 eslint: no-undef

window.alert('hi')   // ✓ ok

连续两行的空行是不允许的

 eslint: no-multiple-empty-lines

// ✓ ok 
var value = 'hello world'
console.log(value)
// ✗ avoid 
var value = 'hello world'


console.log(value)

三目运算操作时,要不保持一行完成,要不将?和:保持在首个字符

 eslint: operator-linebreak

// ✓ ok 
var location = env.development ? 'localhost' : 'www.api.com'

// ✓ ok 
var location = env.development
  ? 'localhost'
  : 'www.api.com'

// ✗ avoid 
var location = env.development ?
  'localhost' :
  'www.api.com'

 变量声明时保持各个变量单独成行。

eslint: one-var

// ✓ ok 
var silent = true
var verbose = true

// ✗ avoid 
var silent = true, verbose = true

// ✗ avoid 
var silent = true,
    verbose = true

用()包裹赋值语句,以免程序员误解为===比较.

eslint: no-cond-assign

// ✓ ok 
while ((m = text.match(expr))) {
  // ... 
}

// ✗ avoid 
while (m = text.match(expr)) {
  // ... 
}

在单行语句块前后增加空格

eslint: block-spacing

function foo () {return true}    // ✗ avoid 
function foo () { return true }  // ✓ ok

使用驼峰命名变量和函数

eslint: camelcase

  function my_function () { }    // ✗ avoid 
  function myFunction () { }     // ✓ ok 

  var my_var = 'hello'           // ✗ avoid 
  var myVar = 'hello'

results matching ""

    No results matching ""