外掛
vscode必須安裝外掛Prettier - Code formatter, 格式化程式碼快捷鍵
Shift + Alt + F
Prettier is an opinionated code formatter。 It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary。
importClass和require誰先誰後
runtime。loadDex(“。/yashu。dex”);importClass(android。graphics。Rect);let yashu = require(“。/yashu”);
介面
介面優先顯示, 其他操作靠後, 緩解使用者焦慮
命名約定
避免單個字元名,讓你的變數名有描述意義。
// badfunction q() { // 。。。stuff。。。}// goodfunction query() { // 。。stuff。。}
當命名物件、函式和例項時使用駝峰命名規則
// badvar OBJEcttsssss = {};var this_is_my_object = {};var this-is-my-object = {};function c() {};var u = new user({ name: ‘Bob Parr’});// goodvar thisIsMyObject = {};function thisIsMyFunction() {};var user = new User({ name: ‘Bob Parr’});
當命名建構函式或類時使用駝峰式大寫
// badfunction user(options) { this。name = options。name;}var bad = new user({ name: ‘nope’});// goodfunction User(options) { this。name = options。name;}var good = new User({ name: ‘yup’});
命名私有屬性時前面加個下劃線 _
// badthis。__firstName__ = ‘Panda’;this。firstName_ = ‘Panda’;// goodthis。_firstName = ‘Panda’;
當儲存對 this 的引用時使用 _this。
// badfunction() { var self = this; return function() { console。log(self); };}// badfunction() { var that = this; return function() { console。log(that); };}// goodfunction() { var _this = this; return function() { console。log(_this); };}
檔案命名規範
谷歌
File names must be all lowercase and may include underscores (_) or dashes (-), but no additional punctuation。 Follow the convention that your project uses。 Filenames’ extension must be 。js。
github
What is the javascript filename naming convention?
https://stackoverflow。com/questions/7273316/what-is-the-javascript-filename-naming-convention
其他1
Js 檔案命名規範
字母全部小寫
不要帶空格
用破折號(-)連線單詞
庫檔案可用逗點(。),用於體現版本或從屬關係
Demo
vue。min。js
vue-router。js
jquery。form。js
jquery-1。4。2。min。js
其他2
1、專案命名
全部採用小寫方式,以下劃線分割戰場
例如:come_money
2、目錄命名
參照專案命名,如有複數結構時,採用複數命名法
例如: moneys,assets,components。。。。
3、js、css、less、sass、 stylus檔案命名
全部採用小駝峰命名規則
例如: comeMoney。js、moneyCome。css、moneyCome。stylus
4、VUE元件Components命名
所有元件名字大駝峰格式
例如: ComeMoney。vue、MoneyCome。vue
上面的慣例僅供參考,最終還是尊重個人習慣。不過如果你在專案中引用了某個框架或庫,就最好優先使用他們的命名習慣。另外,一個專案中最好統一使用一種命名規則,這樣方便自己和其他開發人員識別。
物件
請使用物件方法的簡寫方式, 屬性不可簡寫, 方法可以簡寫
// badconst item = { value: 1, addValue: function (val) { return item。value + val }}// goodconst item = { value: 1, addValue (val) { return item。value + val }}
不要直接使用 Object。prototype 的方法, 例如 hasOwnProperty, propertyIsEnumerable 和 isPrototypeOf 方法
原因:這些方法可能會被物件自身的同名屬性覆蓋 - 比如 { hasOwnProperty: false } 或者物件可能是一個 null 物件(Object。create(null))
// badconsole。log(object。hasOwnProperty(key))// goodconsole。log(Object。prototype。hasOwnProperty。call(object, key))// bestconst has = Object。prototype。hasOwnProperty // cache the lookup once, in module scope。console。log(has。call(object, key))
陣列
當你需要複製陣列時使用slice
var len = items。length, itemsCopy = [], i;// badfor (i = 0; i < len; i++) { itemsCopy[i] = items[i];}// gooditemsCopy = items。slice();
使用slice將類陣列的物件轉成陣列
function trigger() { var args = Array。prototype。slice。call(arguments); 。。。}
解構賦值
當需要使用陣列的多個值時,請使用解構賦值
const arr = [1, 2, 3, 4]// badconst first = arr[0]const second = arr[1]// goodconst [first, second] = arr
字串
字串太長的時候,請不要使用字串連線符換行 \,而是使用 +
const str = ‘牙叔教程 牙叔教程 牙叔教程’ + ‘牙叔教程 牙叔教程 牙叔教程’ + ‘牙叔教程 牙叔教程’
不要在字串中使用不必要的跳脫字元
// badconst foo = ‘\’this\‘ \i\s \“quoted\”’// goodconst foo = ‘\’this\‘ is “quoted”’
程式設計時使用join而不是字串連線來構建字串
var items, messages, length, i;messages = [{ state: ‘success’, message: ‘This one worked。’},{ state: ‘success’, message: ‘This one worked as well。’},{ state: ‘error’, message: ‘This one did not work。’}];length = messages。length;// badfunction inbox(messages) { items = ‘
- ’; for (i = 0; i < length; i++) { items += ‘
- ’ + messages[i]。message + ‘ ’; } return items + ‘
- ’ + items。join(‘
- ’) + ‘
函式
函式表示式
// 匿名函式表示式var anonymous = function() { return true;};// 有名函式表示式var named = function named() { return true;};// 立即呼叫函式表示式(function() { console。log(‘Welcome to the Internet。 Please follow me。’);})();
用圓括號包裹自執行匿名函式
(function () { console。log(‘Welcome to the Internet。 Please follow me。’)}())
不要在一個非函式塊裡宣告一個函式,把那個函式賦給一個變數。
注:
ECMA-262定義把塊定義為一組語句,函式宣告不是一個語句。閱讀ECMA-262對這個問題的說明。
// badif (currentUser) { function test() { console。log(‘Nope。’); }}// goodif (currentUser) { var test = function test() { console。log(‘Yup。’); };}
絕對不要把引數命名為 arguments, 這將會逾越函式作用域內傳過來的 arguments 物件。
// badfunction nope(name, options, arguments) { // 。。。stuff。。。}// goodfunction yup(name, options, args) { // 。。。stuff。。。}
箭頭函式
當你必須使用函式表示式(傳遞匿名函式)時,使用箭頭函式標記
// bad[1, 2, 3]。map(function (x) { const y = x + 1 return x * y})// good[1, 2, 3]。map((x) => { const y = x + 1 return x * y})
物件屬性
使用 。 來訪問物件屬性
const joke = { name: ‘haha’, age: 28}// badconst name = joke[‘name’]// goodconst name = joke。name
當訪問的屬性是變數時使用 []
const luke = { jedi: true, age: 28,}function getProp (prop) { return luke[prop]}const isJedi = getProp(‘jedi’)
變數宣告
在作用域頂部宣告變數,避免變數宣告和賦值引起的相關問題。
// badfunction() { test(); console。log(‘doing stuff。。’); //。。other stuff。。 var name = getName(); if (name === ‘test’) { return false; } return name;}// goodfunction() { var name = getName(); test(); console。log(‘doing stuff。。’); //。。other stuff。。 if (name === ‘test’) { return false; } return name;}// badfunction() { var name = getName(); if (!arguments。length) { return false; } return true;}// goodfunction() { if (!arguments。length) { return false; } var name = getName(); return true;}
將所有的 const 和 let 分組
// badlet aconst blet cconst dlet e// goodconst bconst dlet alet clet e
變數不要進行鏈式賦值
原因:變數鏈式賦值會建立隱藏的全域性變數
// bad(function example() { // JavaScript interprets this as // let a = ( b = ( c = 1 ) ); // The let keyword only applies to variable a; variables b and c become // global variables。 let a = b = c = 1}())console。log(a) // throws ReferenceErrorconsole。log(b) // 1console。log(c) // 1// good(function example() { let a = 1 let b = a let c = a}())console。log(a) // throws ReferenceErrorconsole。log(b) // throws ReferenceErrorconsole。log(c) // throws ReferenceError// the same applies for `const`
不允許出現未被使用的變數
原因:宣告但未被使用的變數通常是不完全重構犯下的錯誤。這種變數在程式碼裡浪費空間並會給讀者造成困擾
// badvar some_unused_var = 42// Write-only variables are not considered as used。var y = 10y = 5// A read for a modification of itself is not considered as used。var z = 0z = z + 1// Unused function arguments。function getX (x, y) { return x}// goodfunction getXPlusY (x, y) { return x + y}const x = 1const y = a + 2alert(getXPlusY(x, y))// ‘type’ is ignored even if unused because it has a rest property sibling。// This is a form of extracting an object that omits the specified keys。const { type, 。。。coords } = data// ‘coords’ is now the ‘data’ object without its ‘type’ property。
Hoisting
var 存在變數提升的情況,即 var 宣告會被提升至該作用域的頂部,但是他們的賦值並不會。而 const 和 let 並不存在這種情況,他們被賦予了 Temporal Dead Zones, TDZ, 瞭解 typeof 不再安全很重要
function example () { console。log(notDefined) // => throws a ReferenceError}function example () { console。log(declareButNotAssigned) // => undefined var declaredButNotAssigned = true}function example () { let declaredButNotAssigned console。log(declaredButNotAssigned) // => undefined declaredButNotAssigned = true}function example () { console。log(declaredButNotAssigned) // => throws a ReferenceError console。log(typeof declaredButNotAssigned) // => throws a ReferenceError const declaredButNotAssigned = true}
匿名函式的變數名會提升,但函式內容不會
function example () { console。log(anonymous) // => undefined anonymous() var anonymous = function () { console。log(‘test’) }}
命名的函式表示式的變數名會被提升,但函式名和函式函式內容並不會
function example() { console。log(named) // => undefined named() // => TypeError named is not a function superPower() // => ReferenceError superPower is not defined var named = function superPower () { console。log(‘Flying’) }}function example() { console。log(named) // => undefined named() // => TypeError named is not a function var named = function named () { console。log(‘named’) }}
比較運算子&相等
使用 === 和 !== 而非 == 和 !=,eslint: eqeqeq
條件宣告例如 if 會用 ToBoolean 這個抽象方法將表示式轉成布林值並遵循如下規則
Objects 等於 true
Undefined 等於 false
Null 等於 false
Booleans 等於 布林值
Numbers 在 +0, -0, 或者 NaN 的情況下等於 false, 其他情況是 true
Strings 為 ‘’ 時等於 false, 否則是 true
if ([0] && []) { // true // 陣列(即使是空陣列)也是物件,物件等於true}
使用快捷方式。
// badif (name !== ‘’) { // 。。。stuff。。。}// goodif (name) { // 。。。stuff。。。}// badif (collection。length > 0) { // 。。。stuff。。。}// goodif (collection。length) { // 。。。stuff。。。}
分號
自執行函式前後必須加分號
const test = ‘牙叔教程’;(() => { const str = ‘簡單易學’})();
塊
給所有多行的塊使用大括號
// badif (test) return false;// goodif (test) return false;// goodif (test) { return false;}// badfunction() { return false; }// goodfunction() { return false;}
註釋
使用 /** 。。。 */ 進行多行註釋,包括描述,指定型別以及引數值和返回值
// bad// make() returns a new element// based on the passed in tag name//// @param
使用 // 進行單行註釋,在評論物件的上面進行單行註釋,註釋前放一個空行。
// badvar active = true; // is current tab// good// is current tabvar active = true;// badfunction getType() { console。log(‘fetching type。。。’); // set the default type to ‘no type’ var type = this。_type || ‘no type’; return type;}// goodfunction getType() { console。log(‘fetching type。。。’); // set the default type to ‘no type’ var type = this。_type || ‘no type’; return type;}
如果你有一個問題需要重新來看一下或如果你建議一個需要被實現的解決方法的話需要在你的註釋前面加上 FIXME 或 TODO 幫助其他人迅速理解
function Calculator() { // FIXME: shouldn‘t use a global here total = 0; return this;}
function Calculator() { // TODO: total should be configurable by an options param this。total = 0; return this;}
存取器
屬性的存取器函式不是必需的
如果你確實有存取器函式的話使用getVal() 和 setVal(’hello‘)
// baddragon。age();// gooddragon。getAge();// baddragon。age(25);// gooddragon。setAge(25);
如果屬性是布林值,使用isVal() 或 hasVal()
// badif (!dragon。age()) { return false;}// goodif (!dragon。hasAge()) { return false;}
可以建立get()和set()函式,但是要保持一致
function Jedi(options) { options || (options = {}); var lightsaber = options。lightsaber || ’blue‘; this。set(’lightsaber‘, lightsaber);}Jedi。prototype。set = function(key, val) { this[key] = val;};Jedi。prototype。get = function(key) { return this[key];};
構造器
給物件原型分配方法,而不是用一個新的物件覆蓋原型,覆蓋原型會使繼承出現問題。
function Jedi() { console。log(’new jedi‘);}// badJedi。prototype = { fight: function fight() { console。log(’fighting‘); }, block: function block() { console。log(’blocking‘); }};// goodJedi。prototype。fight = function fight() { console。log(’fighting‘);};Jedi。prototype。block = function block() { console。log(’blocking‘);};
方法可以返回 this 幫助方法可鏈。
// badJedi。prototype。jump = function() { this。jumping = true; return true;};Jedi。prototype。setHeight = function(height) { this。height = height;};var luke = new Jedi();luke。jump(); // => trueluke。setHeight(20) // => undefined// goodJedi。prototype。jump = function() { this。jumping = true; return this;};Jedi。prototype。setHeight = function(height) { this。height = height; return this;};var luke = new Jedi();luke。jump() 。setHeight(20);
可以寫一個自定義的toString()方法,但是確保它工作正常並且不會有副作用。
function Jedi(options) { options || (options = {}); this。name = options。name || ’no name‘;}Jedi。prototype。getName = function getName() { return this。name;};Jedi。prototype。toString = function toString() { return ’Jedi - ‘ + this。getName();};
參考
Google JavaScript Style Guide
https://google。github。io/styleguide/jsguide。html
aotu前端程式碼規範
javascriptCodeStyle
https://github。com/airbnb/javascript
名人名言
思路是最重要的, 其他的百度, bing, stackoverflow, 安卓文件, autojs文件, 最後才是群裡問問
——- 牙叔教程
宣告
部分內容來自網路
本教程僅用於學習, 禁止用於其他用途