前端代码规范JS/ES6

1.声明变量

1.1建议不再使用var,而使用let 和const 。

ES6提出了两个新的声明变量的命令:let 和 const 这两个声明实现了块作用域,同时屏蔽了遍历提升
对于常量或不修改的变量声明使用const,对于只在当前作用域下有效的变量,应使用let,全局变量可以继续使用var。将所有 const 变量放在一起,然后将所有 let 变量放在一起

const foo = 1;

let foo1 = 2;
let bar = foo;
bar = 9;
foo1 = 3;

console.log(foo, bar); // => 1, 9
console.log(foo, bar, str); // => 1, 9,'ouven'

块作用域示例

// const and let only exist in the blocks they are defined in.
{
  let a = 1;
  const b = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError

1.2使用字面量语法创建对象而不是构造函数

使用字面量让语法更简洁
构造函数声明的对象为object ,会对String,Number,Boolean等非引用对象操作造成不必要的麻烦

不推荐

    let a = new String("a")
    let b = new Number(1)
    let c = new Boolean(true)
    let d = new Array()


    console.log(a);         //String {"a"}
    console.log(b);         //Number {1}
    console.log(c);         //Boolean {true}
    console.log(d);         //[]
    console.log(typeof a);  //object
    console.log(typeof b);  //object
    console.log(typeof c);  //object
    console.log(typeof d);  //object

推荐

    let a = "a"
    let b =1
    let c = true
    let d = []

    console.log(a);         //a
    console.log(b);         //1
    console.log(c);         //true
    console.log(d);         //[]
    console.log(typeof a);  //string
    console.log(typeof b);  //number
    console.log(typeof c);  //boolean
    console.log(typeof d);  //object

2.字符串操作String

2.1灵活使用template string

  • 建议拼接字符串不使用“+”,而使用template string
  • 需要换行的字符串建议使用template string

不推荐

 const a = "foobar";
 const b = 'foo'+a+'bb';
 
 const c = func()+'word'
 function func() {
    return 'Hello';
 }
 
 const d = 'This is a super long error that \
  was thrown because of Batman. \
  When you stop to think about \
  how Batman had anything to do \
  with this, you would get nowhere \
  fast.';
  
function sayHi(name) {
  return 'How are you, ' + name + '?';
}

推荐

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

const c = `${func()}word`
 function func() {
    return 'Hello';
 }
 
const d = `This is a super long error that 
  was thrown because of Batman. 
  When you stop to think about 
  how Batman had anything to do 
  with this, you would get nowhere 
  fast.`;

function sayHi(name) {
  return `How are you, ${name}?`;
}

3.布尔操作Boolean

禁止字符串和数字直接和boolean比较,if判断和三元表达式会自动使用Boolean的构造函数来解析他们

//Boolean and String
"true"==true
"false" ==false
"HelloWord" !=false  //Any word except false
"HelloWord" !=true   //Any word except true   

//Boolean and Number
"1"==true
"0" ==false
"2" !=false    //Any word except 0
"2" !=true      //Any word except 1

数字在if表达式中

	// a typeof Number
     if(a){  //等价于if(new Boolean(a))
         console.log("这算是一个非零数字");
     }else{
         console.log("这个数字是零");
     }
     
    // a typeof String
     if(a){   //等价于if(new Boolean(a))
         console.log("这是一个有效的非空字符串");
     }else{
         console.log("这是‘’、null、undefined");
     }

4.数组操作Array

4.1使用push来添加数组元素

不推荐

const someStack = [];
someStack[0] = 'technicalStandard';
someStack[someStack.length] = 'HelloWord';

推荐

const someStack = [];
someStack.push('technicalStandard');
someStack.push('HelloWord');

4.2数组拷贝

推荐使用 ... 展开语法来拷贝数组,
也可以使用 Array.from、Array.of等数组的新的内置API,Array新api用于适合的场景
不推荐

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

推荐

const foo = [1,2,3];
const nodes = Array.from(foo);

推荐

const itemsCopy = [...items];

4.3使用数组解构完成赋值

将数组成员赋值给变量时,使用数组解构

不推荐

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

推荐

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

5.日期

5.1和其他语言使用时间戳格式对接

前后台交互的推荐使用时间戳。不同语言、不同浏览器默认的时间格式各不相同,但是所有语言对,时间戳的格式都有支持,尤其需要兼容IE浏览器,强烈推荐使用时间戳

不推荐

//从后台获取    
let dataTime = new Data("2020-04-09 08:08:08")   //err in IE 

//返给后台
let times = new Date()  //Google  Wed Apr 29 2020 16:18:58 GMT+0800 (中国标准时间)
                        //IE 10   Wed Apr 29 16:29:56 UTC+0800 2020 

推荐

//从后台获取  1588148379974
let dataTime = new Data(1588148379974)  //Wed Apr 29 2020 16:18:58 GMT+0800 (中国标准时间)

//返给后台
let times = new Date().getTime()   //1588148379974

6.对象

6.1使用对象字面量创建对象

不推荐

var item = new Object();

推荐

let item = {};

6.2不要使用保留字(reserved words)作为键,否则在 IE8 下将出错

不推荐

let superman = {
  class: 'superhero',
  default: { clark: 'kent' },
  private: true
};

推荐

var superman = {
  klass: 'superhero',
  defaults: { clark: 'kent' },
  hidden: true
};

6.3使用定义对象方法的简短形式

不推荐

const atom = {
  addValue: function (value) {
    return atom.value + value;
  }
};

推荐

const atom = {
  addValue(value) {
    return atom.value + value;
  }
};

6.4使用定义对象属性的简短形式

使用定义对象属性的简短形式,书写起来更加简单,并且可以自描述。这里和es5有些不同,需要注意下

不推荐

  const lukeSkywalker = 'Luke Skywalker';
  const obj = {
    lukeSkywalker: lukeSkywalker
  };

推荐

  const lukeSkywalker = 'Luke Skywalker';
  const obj = {
    lukeSkywalker
  };

6.5将所有简写的属性写在对象定义的最顶部

将所有简写的属性写在对象定义的最顶部,这样可以更加方便地知道哪些属性使用了简短形式。

不推荐

const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
 
const obj = {
  episodeOne: 1,
  twoJedisWalkIntoACantina: 2,
  lukeSkywalker,
  episodeThree: 3,
  mayTheFourth: 4,
  anakinSkywalker
};

推荐

const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
 
const obj = {
  lukeSkywalker,
  anakinSkywalker,
  episodeOne: 1,
  twoJedisWalkIntoACantina: 2,
  episodeThree: 3,
  mayTheFourth: 4
};

6.6属性访问

使用点 . 操作符来访问常量属性,使用点 [] 操作符来访问变量属性

不推荐

const luke = {
  jedi: true,
  age: 28
};

const isJedi = luke['jedi'];

推荐

const luke = {
  jedi: true,
  age: 28
};
const myKey= 'age'
const isJedi = luke.jedi;
const isSge = luke[myKey];

7.方法与函数

7.1使用函数声明而不是函数表达式

函数声明拥有函数名,在调用栈中更加容易识别。并且,函数声明会整体提升,而函数表达式只会提升变量本身。这条规则也可以这样描述,始终使用箭头函数来代替函数表达式。

不推荐

const foo = function () {
};

推荐

function foo() {
}

7.2禁止在非函数块中进行函数声明

绝对不要在一个非函数块(if,while,等等)里声明一个函数,把那个函数赋给一个变量。浏览器允许你这么做,但是它们解析不同

不推荐

if (currentUser) {
  function test() {
    console.log('Nope.');
  }
}

推荐

if (currentUser) {
  var test = function test() {
    console.log('Yup.');
  };
}

7.3函数/方法的参数不能使用js保留关键字

例如不要把参数命名为 arguments,虽然可以运行,但这将会覆盖函数作用域内传过来的 arguments 对象

不推荐

function nope(name, options, arguments) {
  // ...stuff...
}

推荐

function yup(name, options, args) {
  // ...stuff...
}

7.4使用展开语法接收更多参数

不要使用 arguments,使用 … 操作符来代替

… 操作符可以明确指定你需要哪些参数,并且得到的是一个真实的数组,而不是 arguments 这样的类数组对象。

不推荐

function concatenateAll() {
  const args = Array.prototype.slice.call(arguments);
  return args.join('');
}

推荐

function concatenateAll(...args) {
  return args.join('');
}

7.5使用函数参数默认值语法,而不是修改函数的实参

不推荐

function handleThings(opts) {
  opts = opts || {};
}

不推荐

function handleThings(opts) {
  if (opts === void 0) {
    opts = {};
  }
}

推荐

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

7.6使用解构语法接收指定参数

不推荐

function getFullName(user){
    const firstName  = user.firstName ;
    const lastName = user.lastName ;
    return `${firstName} ${ lastName }`;
} 

不推荐

function getFullName(user){
    const { firstName ,lastName } = user;
    return `${firstName} ${ lastName }`;
} 

推荐

 function getFullName({ firstName ,lastName }){
    return `${firstName} ${lastName}`;
 }

7.7使用解构语法返回更多结果

推荐使用解构语法返回多个结果,这样生成key-value形式的多个参数
不推荐使用数组返回多个结果
不推荐

function anotherFun() {
  const one = 1, two = 2, three = 3;
  return [one, two, three];
}
const [one, three, two] = anotherFun(); // 顺序乱了
// one = 1, two = 3, three = 2

推荐

function anotherFun() {
  const one = 1, two = 2, three = 3;
  return { one, two, three };
}
const { one, three, two } = anotherFun(); // 不用管顺序
// one = 1, two = 2, three = 3

7.8使用数组解构语法交换值

不推荐

let x = 1;
let y = 2;
let temp;
temp = x;
x = y;
y = temp;

推荐

let x = 1;
let y = 2;
[x, y] = [y, x]; // 交换变量

7.9合并相同if分支

  • 若一个方法中多个if返回的结果相同,让他们合并为一个分支,让代码更加优雅
  • 优先返回参数校验的return分支

不推荐

function func(params){
      if(params){
        if(params instanceof String){
          //More code ....
        }else{
          return ""
        }
      }else{
        return ""
      }
    }

不推荐

function func(params){
      if(params&&params instanceof String){
          //More code....
      }else{
        return ""
      }
    }

推荐

function func(params){
      if(!params||!params instanceof String){
          return ""
      }
      //More code....
    }

7.10使用更简洁箭头函数 Arrow Functions

箭头函数提供了更简洁的语法,建议简单的函数(尤其是匿名函数),使用箭头函数来让代码更优雅

不推荐

    let arr = [1,2,3,5,6,4].filter(
         function(value,index){
             return value<=3
         }
     )

不推荐

let arr = [1,2,3,5,6,4].filter(
        (value,index)=>{
            return value<3
        }
    )
let arr = [1,2,3,5,6,4].filter(
        value=>{
            return value<3
        }
    )    

推荐

let arr = [1, 2, 3, 5, 6, 4].filter(value => value < 3);

7.11使用箭头函数来保留this对象

并且箭头函数中 this 对象的指向是不变的,this 对象绑定定义时所在的对象,这通常是我们想要的。

不推荐

      let _self = this;
      get().then(function(res){
        //_self..
      })

推荐

      get().then(res => {
        //this..
      })

8.注释

注释是你自己与你的小伙伴们了解代码写法和目的的唯一途径。特别是在写一些看似琐碎的无关紧要的代码时,由于记忆点不深刻,注释就变得尤为重要了。

编写自解释代码只是一个传说,没有任何代码是可以完全自解释的。而代码注释,则是永远也不嫌多。

8.1方法中使用//注释

当你写注释时一定要注意:不要写你的代码都干了些什么,而要写你的代码为什么要这么写,背后的考量是什么。当然也可以加入所思考问题或是解决方案的链接地址。

不推荐

var offset = 0;
 
if(includeLabels) {
  // Add offset of 20
  offset = 20;
}

不推荐

.example {
 var offset = 0;
 
if(includeLabels) {
  /** If the labels are included we need to have a minimum offset of 20 pixels
   * We need to set it explicitly because of the following bug: http://somebrowservendor.com/issue-tracker/ISSUE-1
   */
  offset = 20;
}

推荐

.example {
 var offset = 0;
 
if(includeLabels) {
  // If the labels are included we need to have a minimum offset of 20 pixels
  // We need to set it explicitly because of the following bug: http://somebrowservendor.com/issue-tracker/ISSUE-1
  offset = 20;
}

8.2方法/函数使用JSDoc注释

JSDoc 注释规则
JSDoc注释一般应该放置在方法或函数声明之前,它必须以/ **开始,以便由JSDoc解析器识别。其他任何以 /*/*** 或者超过3个星号的注释,都将被JSDoc解析器忽略。
推荐使用@来使注释调理更加清晰

常用的注解

  • @MethodDescription 方法的说明
  • @constructor明确一个函数是某个类的构造函数。
  • @param 参数注释
  • @return 返回值注释
  • @example 示例注释
  • @description: 方法的细致描述
  • @overview对当前代码文件的描述。
  • @copyright代码的版权信息。
  • @author []代码的作者信息。
  • @version当前代码的版本。
  • @date 方法的创建时间

示例

/**
* @MethodDescription: Book类,代表一个书本.
* @constructor 
* @description:根据书本的标题、作者创建一个书的实例
* @param {string} title - 书本的标题.
* @param {string} author - 书本的作者.
* @author icebound。
* @date: 2020-04-29 16:54:40
* @version v1.0.0
*/

functionBook(title, author){
    this.title=title;
    this.author=author;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值