首頁 > web前端 > js教程 > 主體

日常js開發規範

韦小宝
發布: 2018-05-11 11:28:16
原創
1860 人瀏覽過

這篇文章我們來講一下JavaScript日常開發規範,讓大家往後的JavaScript日常開發寫出的js程式碼更規範,有興趣的同學可以來看看這篇文章!日常開發規範還是很重要的!

前端入坑依賴前後後寫了好幾個項目,在用JavaScript寫交互邏輯的時候,或多或少寫了一些垃圾程式碼,如全域變數污染、程式碼復用性差、簡潔性不高等直接給程式碼後期維護的造成一些困惑。以下是一些JS編碼方面有待改進的地方,可直接在開發中加以應用,致力於寫出更優雅的程式碼​​。

說到程式碼規範,我們或許會想到ESLint規則,下面的規範有涉及到ESLint規則的進行了相關的說明,也許在你使用ESLint的時候出現相關報錯提示也可以從中或許一些幫助。

1.變數宣告

1.1不要用var宣告變量,盡量使用const 

eslint: prefer-const, no-const -assign

避免使用var能夠減少全域變數污染問題,使用const確保宣告的變數是唯一的,無法在對其進行重新賦值運算。

//bad
var a = 1;
//best
const a = 1;
登入後複製

1.2如果需要宣告可變動的引用,那麼使用let代替var

eslint: no-var jscs: disallowVar

#let屬於目前{}中的一個區塊級作用域,而var屬於函數作用域

#
//bad
var count = 1;
if (true) {
	var count = 2;
}
console.log(count)


//best
let count = 1;
if (true) {
	let count = 2;
}
console.log(count)
登入後複製

1.3將宣告的let和const分組

能夠提高程式碼可讀性。

//bad
let a = 1;
const obj = {};
let num = 0;
const page = 10;

//best
let a = 1;
let num = 0;
const obj = {};
const page = 10;
登入後複製

1.4將let和const宣告的變數放在適當位置

因為let和const被賦予了一種稱為【暫時性死區(Temporal Dead Zones, TDZ )】的概念,也就決定了他們宣告的變數不會進行變數提升。而var宣告的變數會被提升到作用域頂端。

2.使用物件

2.1使用字面量建立物件

#eslint: no-new-object

#
//bad
const obj = new Object();

//good
const obj = {};
登入後複製

2.2物件的方法是用簡寫形式

// bad
const atom = {
  value: 1,

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

// good
const atom = {
  value: 1,

  addValue(value) {
    return atom.value + value;
  },
};
登入後複製

2.3物件的屬性也使用簡寫形式

##eslint: object-shorthand jscs: requireEnhancedObjectLiterals

const hello = "你好";

//bad
const obj = {
	hello:hello
};

//best
const obj = {
	hello,
};
登入後複製

2.4不要直接使用Object.prototype的方法,如:hasOwnProperty, propertyIsEnumerable, isPrototypeOf 等

// bad
console.log(object.hasOwnProperty(key));

// good
console.log(Object.prototype.hasOwnProperty.call(object, key));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
const has = require('has');
…
console.log(has.call(object, key));
登入後複製

2.5物件的淺拷貝最好使用... 而不是Object.assign()

// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original`
delete copy.a; // so does this

// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }

// good
const 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 }
登入後複製

使用Object.assign()會產生一些意想不到的問題。

3.使用陣列

3.1使用字面量建立陣列

eslint: no-array-constructor

// bad
const arr= new Array();

// good
const arr= [];
登入後複製

3.2使用擴充運算子...複製數組

// bad
const arr= new Array();

// good
const arr= [];

// bad
const len = arr.length;
const arrCopy = [];
let i;

for (i = 0; i < len; i++) {
  arrCopy[i] = arr[i];
}

// good
const arrCopy = [...arr];
登入後複製

3.3使用Array.from把一個類別數組轉成數組

const list = document.getElementsByTagName("li");
const liNodes = Array.from(list);
登入後複製

4.函數

4.1使用函數宣告代替

函數表達式

為什麼?因為函數宣告的函數會先被識別,進行變數提升(hoisted),而函數表達式只會把函數的引用變數名稱提升(即變數提升)。

// bad
  const fn= function () {
  };

  // good
  function fn() {
  }
登入後複製

4.2不要再一個非函數程式碼區塊中(if,else,while等)宣告函數,  而是把那個函數賦給一個變數。即使前者不會報錯,但是瀏覽器的解析方式是不同的。

// bad
if (ifLogin) {
  function test() {
    console.log(&#39; logged&#39;);
  }
}

// good
let test;
if (ifLogin) {
  test = () => {
    console.log(&#39; logged&#39;);
  };
}
登入後複製

4.3避免使用arguments,而是用rest語法... 替代

原因是arguments是一個類別數組,沒有數組特有的方法,而...能夠明確你傳入的參數,並且是真正的陣列。

// bad
  function myconcat() {
    const args = Array.prototype.slice.call(arguments);
    return args.join(&#39;&#39;);
  }

  // good
  function myconcat(...args) {
    return args.join(&#39;&#39;);
  }
登入後複製

5.箭頭函數

5.1當你必須使用函數表達式(或需要傳遞一個匿名函數)時候,可以使用箭頭函數來代替。

原因是使用新的函數會創建一個新的函數作用域,這樣就會改變當前this的指向,而箭頭函數會創建一個新的this執行環境,能夠將當前環境的this繼續傳遞下去;寫法也更為簡潔。

當你的函數較為複雜的時候,這時候使用箭頭函數就容易出問題,可以用函數宣告來代替。

// bad
  [1, 3, 5].map(function (x) {
    return x * x;
  });

  // good
  [1, 3, 5].map((x) => {
    return x * x;
  });
登入後複製

5.2

如果一個函數適合用一行寫出並且只有一個參數,那就把花括號、圓括號和 return 都省略掉。如果不是,那就不要省略。
 // good
  [1, 2, 3].map(x => x * x);

  // good
  [1, 2, 3].reduce((total, n) => {
    return total + n;
  }, 0);
登入後複製

6.建構器

6.1總是使用class,避免直接操作prototype屬性

這樣寫比較為簡潔。

// 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;
    }
  }
登入後複製

7.模組開發

7.1利用模組的思想寫業務。

使用模組編寫邏輯業務,可以讓你的程式碼更有整體性和可擴展性。類似的函式庫有seaJS、requireJS

7.2少使用通配符import

这样更能够确保你只有一个模块被你import,而那些不必要的模块不会被import,减少代码体积。

  // bad
  import * as webUI from &#39;./WEB&#39;;

  // good
  import webUI from &#39;./WEB&#39;;
登入後複製

8.使用高阶函数如map()和reduce()代替for~of

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

  // bad
  let sum = 0;
  for (let num of arr) {
    sum += num;
  }

  sum === 15;

  // good
  let sum = 0;
  arr.forEach((num) => sum += num);
  sum === 15;

  // best (use the functional force)
  const sum = arr.reduce((total, num) => total + num, 0);
  sum === 15;
登入後複製

9.比较运算符

9.1优先使用===和!==而不是==和!=

===和!==不会进行强制类型转换,后者则会

9.2在做if条件判断时强制类型转换规则

  • 对象都会被转为true

  • null、undefined、NaN被转为false

  • 布尔值转为对应的布尔值

  • 数字中+0 -0 0都被计算为false,否则为true

  • 字符串   如果是“”空字符串,被计算为fasle,否则为true

相关推荐:

Web 前端代码规范

JavaScript代码规范和性能整理

HTML(5) 代码规范

以上是日常js開發規範的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!