命名編碼規(guī)范
駝峰式命名法介紹
-Pascal Case 大駝峰式命名法:首字母大寫匆光。eg:StudentInfo套像、UserInfo、ProductInfo
-Camel Case 小駝峰式命名法:首字母小寫终息。eg:studentInfo夺巩、userInfo贞让、productInfo
文件命名
文件名不能含有空格
文件名建議只使用小寫字母,不使用大寫字母柳譬。(但比如說像github的說明類文件喳张,README,則應(yīng)該全部使用大寫)
文件名包含多個(gè)單詞時(shí)征绎,單詞之間建議使用半角的連詞線 ( - ) 分隔蹲姐。
// 反例
├── index.html
├── main.js
└── components
├── pageheader
├── pagearticle
└── pageheader
// 正例
├── index.html
├── main.js
└── components
├── page-header
├── page-article
└── page-header
命名規(guī)范
es6提供了兩個(gè)新的變量命名關(guān)鍵字磨取,const,let人柿。加上var,一共3個(gè)命名關(guān)鍵字忙厌。
怎么用這個(gè)三個(gè)關(guān)鍵字
當(dāng)你的變量能保證不會(huì)被修改凫岖,則用const,如一些常量等
如果是會(huì)一直修改逢净,則使用let
盡量不要使用var
變量
變量命名:
-命名方式:小駝峰式命名方法
-命名規(guī)范:類型+對(duì)象描述的方式哥放,如果沒有明確的類型,就可以使前綴為名詞
javascript變量命名類型 | 變量命名前綴 |
---|---|
array數(shù)組 | a |
boolean布爾值 | b |
float浮點(diǎn)數(shù) | l |
function 函數(shù) | fn |
int 整型 | i |
object 對(duì)象 | o |
regular 正則 | r |
string 字符串 | s |
var aName = [1, 2, 3];
var oBtn = document.getElementById('btn');
function fnName(){};
var iCount = 0;
var sName = "zhuyujia";
函數(shù)
命名方式:小駝峰方式 ( 構(gòu)造函數(shù)使用大駝峰命名法 )
命名規(guī)則:前綴為動(dòng)詞
動(dòng)詞 | 含義 | 返回值 |
---|---|---|
can | 判斷是否可執(zhí)行某個(gè)動(dòng)作 ( 權(quán)限 ) | 函數(shù)返回一個(gè)布爾值 true:可執(zhí)行爹土;false:不可執(zhí)行 |
has | 判斷是否含有某個(gè)值 | 函數(shù)返回一個(gè)布爾值 true:含有此值甥雕;false:不含有此值 |
is | 判斷是否為某個(gè)值 | 函數(shù)返回一個(gè)布爾值 true:為某個(gè)值;false:不為某個(gè)值 |
get | 獲取某個(gè)值 | 函數(shù)返回一個(gè)非布爾值 |
set | 設(shè)置某個(gè)值 | 無返回值胀茵、返回是否設(shè)置成功或者返回鏈?zhǔn)綄?duì)象 |
//是否可閱讀
function canRead() {
return true;
}
//獲取姓名
function getName {
return this.name;
}
常量
-命名方式:全部大寫
-命名規(guī)范:使用大寫字母和下劃線來組合命名社露,下劃線用以分割單詞
var MAX_COUNT = 10;
var URL = 'http://www.baidu.com';
類的成員
-公共屬性和方法:同變量命名方式
-私有屬性和方法:前綴為下劃線(_)后面跟公共屬性和方法一樣的命名方式
function Student(name) {
var _name = name; // 私有成員
// 公共方法
this.getName = function() {
return _name;
}
// 公共方式
this.setName = function(value) {
_name = value;
}
}
var st = new Student('tom');
st.setName('jerry');
console.log(st.getName()); // => jerry:輸出_name私有變量的值
注釋規(guī)范
單行注釋
-單獨(dú)一行://(雙斜線)與注釋文字之間保留一個(gè)空格
-在代碼后面添加注釋://(雙斜線)與代碼之間保留一個(gè)空格,并且//(雙斜線)與注釋文字之間保留一個(gè)空格琼娘。
-注釋代碼://(雙斜線)與代碼之間保留一個(gè)空格峭弟。
// 調(diào)用了一個(gè)函數(shù);1)單獨(dú)在一行
setTitle();
var maxCount = 10; // 設(shè)置最大量脱拼;2)在代碼后面注釋
// setName(); // 3)注釋代碼
多行注釋( / 注釋說明 /)
-若開始(/* 和結(jié)束 / )都在一行瞒瘸,推薦采用單行注釋
-若至少三行注釋時(shí),第一行為/熄浓,最后行為/情臭,其他行以開始,并且注釋文字與*保留一個(gè)空格赌蔑。
/*
* 代碼執(zhí)行到這里后會(huì)調(diào)用setTitle()函數(shù)
* setTitle():設(shè)置title的值
*/
setTitle();
函數(shù)(方法)注釋
-函數(shù)(方法)注釋也是多行注釋的一種谎柄,但是包含了特殊的注釋要求,參照 javadoc(百度百科)
/**
* 函數(shù)說明
* @關(guān)鍵字
*/
注釋名 | 語(yǔ)法 | 含義 | 示例 |
---|---|---|---|
@param | @param參數(shù)名 {參數(shù)類型} 描述信息 | 描述參數(shù)的信息 | @param name {String} 傳入名稱 |
@return | @return{返回類型} 描述信息 | 描述返回值的信息 | @return {Boolean} true:可執(zhí)行;false:不可執(zhí)行 |
@author | @author作者信息 [附屬信息:如郵箱惯雳、日期] | 描述此函數(shù)作者的信息 | @author張三 2019/06/01 |
@version | @versionXX.XX.XX | 描述此函數(shù)的版本號(hào) | @version 1.03 |
@example | @example示例代碼 | @example setTitle('測(cè)試') | 如下 |
/**
- 合并Grid的行
- [@param](/user/param) grid {Ext.Grid.Panel} 需要合并的Grid
- [@param](/user/param) cols {Array} 需要合并列的Index(序號(hào))數(shù)組朝巫;從0開始計(jì)數(shù),序號(hào)也包含石景。
- [@param](/user/param) isAllSome {Boolean} :是否2個(gè)tr的cols必須完成一樣才能進(jìn)行合并劈猿。true:完全一樣拙吉;false(默認(rèn)):不完全一樣
- [@return](/user/return) void
- [@author](/user/author) polk6 2019/06/01
- [@example](/user/example)
- _________________ _________________
- | 年齡 | 姓名 | | 年齡 | 姓名 |
- ----------------- mergeCells(grid,[0]) -----------------
- | 18 | 張三 | => | | 張三 |
- ----------------- - 18 ---------
- | 18 | 王五 | | | 王五 |
- ----------------- -----------------
*/
function mergeCells(grid, cols, isAllSome) {
// Do Something
}
關(guān)于VUE的開發(fā)規(guī)范
下面是vue的生命鉤子
vue2.0 | Description |
---|---|
beforeCreate | 組件實(shí)例剛剛被創(chuàng)建,組件屬性計(jì)算之前揪荣,如data屬性等 |
created | 組件實(shí)例創(chuàng)建完成筷黔,屬性已綁定,但DOM還未生成仗颈,$el屬性還不存在 |
beforeMount | 模板編譯/掛載之前 |
mounted | 模板編譯/掛載之后 |
beforeUpdate | 組件更新之前 |
updated | 組件更新之后 |
activated | for ,組件被激活時(shí)調(diào)用 |
deactivated | for ,組件被移除時(shí)調(diào)用 |
beforeDestory | 組件銷毀前調(diào)用 |
destoryed | 組件銷毀后調(diào)用 |
vue文件基本結(jié)構(gòu)
<template>
<div>
<!--必須在div中編寫頁(yè)面-->
</div>
</template>
<script>
export default {
components : {},//5.注冊(cè)需要用到的組件
props:{},//7.傳遞到本組件的props
data () {//8.組件的 data 必須是一個(gè)函數(shù)
return {
}
},
computed:{},//8
watch:{},//9
//所有的鉤子函數(shù):如created
created(){},//9
methods: {//10
},
}
</script>
<!--聲明語(yǔ)言佛舱,并且添加scoped-->
<style lang="scss" scoped>
</style>
vue文件方法聲明順序
1.副作用 (觸發(fā)組件外的影響)
--el
2.全局感知 (要求組件以外的知識(shí))
--name
--parent
3.組件類型 (更改組件的類型)
--functional
4.模板修改器 (改變模板的編譯方式)
--delimiters
--comments
5.模板依賴 (模板內(nèi)使用的資源)
--components
--directives
--filters
6.組合 (向選項(xiàng)里合并屬性)
--extends
--mixins
7.接口 (組件的接口)
--inheritAttrs
--model
--props/propsData
8.本地狀態(tài) (本地的響應(yīng)式屬性)
--data
--computed
9.事件 (通過響應(yīng)式事件觸發(fā)的回調(diào))
--watch
生命鉤子函數(shù)
---beforeCreate
---created
---beforeMount
---mounted
---beforeUpdate
---updated
---activated
---deactivated
---beforeDestroy
---destroyed
10.非響應(yīng)式的屬性 (不依賴響應(yīng)系統(tǒng)的實(shí)例屬性)
--methods
11.渲染 (組件輸出的聲明式描述)
--template/render
--renderError
元素特性的順序
- v-for
- v-if / v-show
- id
- ref / key / slot
- v-model
- v-on//強(qiáng)烈建議用簡(jiǎn)寫 @,如@change
單文件組件挨决,頂級(jí)元素的順序
<template>
<script>
<style>
按照這個(gè)順序組織代碼就可以请祖。注意style只能在最下面,script和template至少要有一個(gè)
對(duì)象Objects
1.1使用字面量語(yǔ)法創(chuàng)建對(duì)象脖祈。
// bad
const item = new Object();
// good
const item = {};
1.2.當(dāng)創(chuàng)建帶有動(dòng)態(tài)屬性名稱的對(duì)象時(shí)使用計(jì)算的屬性名稱肆捕。
function getKey(k) {
return `a key named ${k}`;
}
// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
1.3.使用對(duì)象方法速記語(yǔ)法。
// bad
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};
1.4.使用對(duì)象屬性速記語(yǔ)法盖高。
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
lukeSkywalker: lukeSkywalker,
};
// good
const obj = {
lukeSkywalker,
};
1.5.將速記屬性分組寫在對(duì)象聲明的開始處慎陵。
const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
episodeOne: 1,
twoJediWalkIntoACantina: 2,
lukeSkywalker,
episodeThree: 3,
mayTheFourth: 4,
anakinSkywalker,
};
// good
const obj = {
lukeSkywalker,
anakinSkywalker,
episodeOne: 1,
twoJediWalkIntoACantina: 2,
episodeThree: 3,
mayTheFourth: 4,
};
1.6.只用引號(hào)引無效標(biāo)識(shí)符的屬性。
// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};
1.7.不要直接調(diào)用 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; // 在模塊作用域內(nèi)席纽,緩存查找一次。
/* or */
import has from 'has';
// ...
console.log(has.call(object, key));
1.8用對(duì)象展開操作符淺復(fù)制對(duì)象撞蚕,優(yōu)先于Object.assign
润梯。使用對(duì)象剩余操作符來獲得一個(gè)省略某些屬性的新對(duì)象。
// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // `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 }
數(shù)組Arrays
2.1使用字面量創(chuàng)建數(shù)組
// bad
const items = new Array();
// good
const items = [];
2.2在向數(shù)組添加元素時(shí)使用push代替直接賦值诈豌。
const someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';
// good
someStack.push('abracadabra');
2.3使用數(shù)組展開操作符 ... 復(fù)制數(shù)組仆救。
// bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i += 1) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items];
2.4使用展開操作符 ...
代替 Array.from,來將一個(gè)類數(shù)組(array-like) 對(duì)象轉(zhuǎn)換成數(shù)組矫渔。
const foo = document.querySelectorAll('.foo');
// good
const nodes = Array.from(foo);
// best
const nodes = [...foo];
2.5實(shí)用 Array.from 代替展開操作符 ...
來映射迭代彤蔽,因?yàn)樗苊饬藙?chuàng)建媒介數(shù)組。
// bad
const baz = [...foo].map(bar);
// good
const baz = Array.from(foo, bar);
2.6在數(shù)組方法回調(diào)中使用 return 語(yǔ)句庙洼。如果函數(shù)體由一個(gè)返回?zé)o副作用的表達(dá)式的單個(gè)語(yǔ)句組成顿痪,那么可以省略返回值
// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
// good
[1, 2, 3].map(x => x + 1);
// bad - 沒有返回值意味著 `memo` 在第一次迭代后變成 undefined
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
const flatten = memo.concat(item);
memo[index] = flatten;
});
// good
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
const flatten = memo.concat(item);
memo[index] = flatten;
return flatten;
});
// bad
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
} else {
return false;
}
});
// good
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
}
return false;
});
2.7如果數(shù)組有多行,請(qǐng)?jiān)诖蜷_和關(guān)閉數(shù)組括號(hào)之前使用換行符油够。
// bad
const arr = [
[0, 1], [2, 3], [4, 5],
];
const objectInArray = [{
id: 1,
}, {
id: 2,
}];
const numberInArray = [
1, 2,
];
// good
const arr = [[0, 1], [2, 3], [4, 5]];
const objectInArray = [
{
id: 1,
},
{
id: 2,
},
];
const numberInArray = [
1,
2,
];
解構(gòu) Destructuring
3.1當(dāng)訪問和使用對(duì)象的多個(gè)屬性時(shí)蚁袭,請(qǐng)使用對(duì)象解構(gòu)
// bad
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
return `${firstName} ${lastName}`;
}
// good
function getFullName(user) {
const { firstName, lastName } = user;
return `${firstName} ${lastName}`;
}
// best
function getFullName({ firstName, lastName }) {
return `${firstName} ${lastName}`;
}
3.2使用數(shù)組解構(gòu)
const arr = [1, 2, 3, 4];
// bad
const first = arr[0];
const second = arr[1];
// good
const [first, second] = arr;
3.3使用對(duì)象解構(gòu)來實(shí)現(xiàn)多個(gè)返回值,而不是數(shù)組解構(gòu)
// bad
function processInput(input) {
// 那么奇跡發(fā)生了
return [left, right, top, bottom];
}
// 調(diào)用者需要考慮返回?cái)?shù)據(jù)的順序
const [left, __, top] = processInput(input);
// good
function processInput(input) {
// 那么奇跡發(fā)生了
return { left, right, top, bottom };
}
// 調(diào)用者只選擇他們需要的數(shù)據(jù)
const { left, top } = processInput(input);
字符串 Strings
4.1字符串使用單引號(hào) ''石咬。
// bad
const name = "Capt. Janeway";
// bad - 模板字面量應(yīng)該包含插值或換行符
const name = `Capt. Janeway`;
// good
const name = 'Capt. Janeway';
4.2超過100個(gè)字符揩悄,導(dǎo)致?lián)Q行的字符串不應(yīng)使用字符串連接符寫成多行。
// bad
const errorMessage = '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.';
// bad
const errorMessage = '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.';
// good
const errorMessage = '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.';
4.3以編程方式構(gòu)建字符串時(shí)鬼悠,請(qǐng)使用模板字符串而不是字符串連接删性。
// bad
function sayHi(name) {
return 'How are you, ' + name + '?';
}
// bad
function sayHi(name) {
return ['How are you, ', name, '?'].join();
}
// bad
function sayHi(name) {
return `How are you, ${ name }?`;
}
// good
function sayHi(name) {
return `How are you, ${name}?`;
}
4.4永遠(yuǎn)不要在字符串上使用 eval() 亏娜,它會(huì)打開太多的漏洞
4.5不要轉(zhuǎn)義字符串中不必要轉(zhuǎn)義的字符
// bad
const foo = '\'this\' \i\s \"quoted\"';
// good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${name}'`;
箭頭函數(shù) Arrow Functions
5.1當(dāng)您必須使用匿名函數(shù)(如在傳遞一個(gè)內(nèi)聯(lián)回調(diào)時(shí)),請(qǐng)使用箭頭函數(shù)表示法
// 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;
});
5.2如果函數(shù)體由一個(gè)返回?zé)o副作用(side effect)的expression(表達(dá)式)的單行語(yǔ)句組成蹬挺,那么可以省略大括號(hào)并使用隱式返回维贺。否則,保留大括號(hào)并使用 return
語(yǔ)句
// bad
[1, 2, 3].map(number => {
const nextNumber = number + 1;
`A string containing the ${nextNumber}.`;
});
// good
[1, 2, 3].map(number => `A string containing the ${number}.`);
// good
[1, 2, 3].map((number) => {
const nextNumber = number + 1;
return `A string containing the ${nextNumber}.`;
});
// good
[1, 2, 3].map((number, index) => ({
[index]: number,
}));
// No implicit return with side effects
function foo(callback) {
const val = callback();
if (val === true) {
// Do something if callback returns true
}
}
let bool = false;
// bad
foo(() => bool = true);
// good
foo(() => {
bool = true;
});
5.3如果表達(dá)式跨多行巴帮,將其包裹在括號(hào)中溯泣,可以提高可讀性。
// bad
['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
httpMagicObjectWithAVeryLongName,
httpMethod,
)
);
// good
['get', 'post', 'put'].map(httpMethod => (
Object.prototype.hasOwnProperty.call(
httpMagicObjectWithAVeryLongName,
httpMethod,
)
));
5.4如果你的函數(shù)只有一個(gè)參數(shù)并且不使用大括號(hào)榕茧,則可以省略參數(shù)括號(hào)垃沦。否則,為了清晰和一致性雪猪,總是給參數(shù)加上括號(hào)栏尚。
// 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;
});
5.5避免使用比較運(yùn)算符(< =, >=)時(shí)起愈,混淆箭頭函數(shù)語(yǔ)法(=>)只恨。
// bad
const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;
// bad
const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;
// good
const itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);
// good
const itemHeight = (item) => {
const { height, largeSize, smallSize } = item;
return height > 256 ? largeSize : smallSize;
};
迭代器 Iterators 和 生成器 Generators
6.1不要使用 iterators(迭代器) 。請(qǐng)使用高階函數(shù)抬虽,例如 map() 和 reduce() 等官觅,而不是像 for-in 或 for-of 這樣的循環(huán)。
const numbers = [1, 2, 3, 4, 5];
// bad
let sum = 0;
for (let num of numbers) {
sum += num;
}
sum === 15;
// good
let sum = 0;
numbers.forEach((num) => {
sum += num;
});
sum === 15;
// best (use the functional force)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;
// bad
const increasedByOne = [];
for (let i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1); } // good const increasedByOne = []; numbers.forEach((num) => {
increasedByOne.push(num + 1);
});
// best (keeping it functional)
const increasedByOne = numbers.map(num => num + 1);
屬性 Properties
7.1使用 點(diǎn)語(yǔ)法(.) 來訪問對(duì)象的屬性
const luke = {
jedi: true,
age: 28,
};
// bad
const isJedi = luke['jedi'];
// good
const isJedi = luke.jedi;
7.2當(dāng)通過變量訪問屬性時(shí)使用中括號(hào) []阐污。
const luke = {
jedi: true,
age: 28,
};
function getProp(prop) {
return luke[prop];
}
const isJedi = getProp('jedi');
7.3求冪時(shí)使用求冪運(yùn)算符 **
// bad
const binary = Math.pow(2, 10);
// good
const binary = 2 ** 10;