<!-- bad -->
<div id="main">
<div class="article">
<div class="header">
<h1>Blog post</h1>
<p>Published: <span>21st Feb, 2015</span></p>
</div>
<p>…</p>
</div>
</div>
複製代碼
<!-- good -->
<main>
<article>
<header>
<h1>Blog post</h1>
<p>Published: <time datetime="2015-02-21">21st Feb, 2015</time></p>
</header>
<p>…</p>
</article>
</main>
複製代碼
<!-- bad -->
<h1>
<figure>
<img alt=Company src=logo.png>
</figure>
</h1>
<!-- good -->
<h1>
<img alt=Company src=logo.png>
</h1>
複製代碼
<!-- bad -->
<!doctype html>
<html lang=en>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8" />
<title>Contact</title>
<link rel=stylesheet href=style.css type=text/css />
</head>
<body>
<h1>Contact me</h1>
<label>
Email address:
<input type=email placeholder=you@email.com required=required />
</label>
<script src=main.js type=text/javascript></script>
</body>
</html>
複製代碼
<!-- good -->
<!doctype html>
<html lang=en>
<meta charset=utf-8>
<title>Contact</title>
<link rel=stylesheet href=style.css>
<h1>Contact me</h1>
<label>
Email address:
<input type=email placeholder=you@email.com required>
</label>
<script src=main.js></script>
</html>
複製代碼
爲每一個 HTML 頁面的第一行添加標準模式(standard mode)的聲明,這樣可以確保在每一個瀏覽器中擁有一致的展示。javascript
<!DOCTYPE html>
<html>
<head>
</head>
</html>
複製代碼
根據 HTML5 規範:css
強烈建議爲 html 根元素指定 lang 屬性,從而爲文檔設置正確的語言。這將有助於語音合成工具肯定其所應該採用的發音,有助於翻譯工具肯定其翻譯時所應遵照的規則等等。
複製代碼
更多關於 lang 屬性的知識能夠從 此規範 中瞭解。html
這裏列出了語言代碼表。前端
<html lang="en">
<!-- ... -->
</html>
複製代碼
IE 支持經過特定的 標籤來肯定繪製當前頁面所應該採用的 IE 版本。除非有強烈的特殊需求,不然最好是設置爲 edge mode,從而通知 IE 採用其所支持的最新的模式。vue
閱讀這篇 stack overflow 上的文章能夠得到更多有用的信息。java
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
複製代碼
經過明確聲明字符編碼,可以確保瀏覽器快速並容易的判斷頁面內容的渲染方式。這樣作的好處是,能夠避免在 HTML 中使用字符實體標記(character entity),從而所有與文檔編碼一致(通常採用 UTF-8 編碼)。node
<head>
<meta charset="UTF-8">
</head>
複製代碼
可用性不該該是過後才考慮的事情。你能夠經過簡單的修改作出不錯的效果,例如:git
<div class=button>
這種粗暴的作法)<!-- bad -->
<h1><img alt="Logo" src="logo.png"></h1>
<!-- good -->
<h1><img alt="My Company, Inc." src="logo.png"></h1>
複製代碼
<!-- bad -->
<!doctype html>
<meta charset=utf-8>
<script src=analytics.js></script>
<title>Hello, world.</title>
<p>...</p>
<!-- good -->
<!doctype html>
<meta charset=utf-8>
<title>Hello, world.</title>
<p>...</p>
<script src=analytics.js></script>
複製代碼
id class name data-xxx src, for, type, href title, alt aria-xxx, role value style
複製代碼
/* bad */
div {
color: red
}
/* good */
div {
color: red;
}
複製代碼
/* bad */
img {
display: block;
}
/* good */
img {
vertical-align: middle;
}
複製代碼
/* bad */
div {
width: 100px;
position: absolute;
right: 0;
}
/* good */
div {
width: 100px;
margin-left: auto;
}
複製代碼
/* bad */
div:first-of-type :last-child > p ~ *
/* good */
div:first-of-type .info
複製代碼
/* bad */
img[src$=svg], ul > li:first-child {
opacity: 0;
}
/* good */
[src$=svg], ul > :first-child {
opacity: 0;
}
複製代碼
/* bad */
.bar {
color: green !important;
}
.foo {
color: red;
}
/* good */
.foo.bar {
color: green;
}
.foo {
color: red;
}
複製代碼
/* bad */
li {
visibility: hidden;
}
li:first-child {
visibility: visible;
}
/* good */
li + li {
visibility: hidden;
}
複製代碼
/* bad */
div h1, div p {
text-shadow: 0 1px 0 #fff;
}
/* good */
div {
text-shadow: 0 1px 0 #fff;
}
複製代碼
/* bad */
div {
transition: all 1s;
top: 50%;
margin-top: -10px;
padding-top: 5px;
padding-right: 10px;
padding-bottom: 20px;
padding-left: 10px;
}
/* good */
div {
transition: 1s;
top: calc(50% - 10px);
padding: 5px 10px 20px;
}
複製代碼
/* bad */
:nth-child(2n + 1) {
transform: rotate(360deg);
}
/* good */
:nth-child(odd) {
transform: rotate(1turn);
}
複製代碼
/* bad */
div:hover {
animation: move 1s forwards;
}
@keyframes move {
100% {
margin-left: 100px;
}
}
/* good */
div:hover {
transition: 1s;
transform: translateX(100px);
}
複製代碼
/* bad */
div {
margin: 0px;
font-size: .9em;
line-height: 22px;
transition: 500ms;
}
/* good */
div {
margin: 0;
font-size: .9rem;
line-height: 1.5;
transition: .5s;
}
複製代碼
/* bad */
div {
color: hsl(103, 54%, 43%);
}
/* good */
div {
color: #5a3;
}
複製代碼
/* bad */
div::before {
content: url(white-circle.svg);
}
/* good */
div::before {
content: "";
display: block;
width: 20px;
height: 20px;
border-radius: 50%;
background: #fff;
}
複製代碼
/* bad */
div {
// position: relative;
transform: translateZ(0);
}
/* good */
div {
/* position: relative; */
will-change: transform;
}
複製代碼
/* Bad CSS */
.selector, .selector-secondary, .selector[type=text] {
padding:15px;
margin:0px 0px 15px;
background-color:rgba(0, 0, 0, 0.5);
box-shadow:0px 1px 2px #CCC,inset 0 1px 0 #FFFFFF
}
/* Good CSS */
.selector,
.selector-secondary,
.selector[type="text"] {
padding: 15px;
margin-bottom: 15px;
background-color: rgba(0,0,0,.5);
box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}
複製代碼
*class應以功能過內容命名,不以表現形式命名,通用且有意義的詞es6
*class與id單詞字母小寫,多個單詞組成時,使用中劃線「-」分隔github
使用on做爲激活狀態的class,使用hover做爲移上元素(hover)的class
一、定位
二、盒模型
三、關於文字
四、關於顏色,背景
五、其餘,如:cursor:pointer
.declaration-order {
/*定位 */
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 100;
/* 盒模型 */
display: block;
box-sizing: border-box;
width: 100px;
height: 100px;
padding: 10px;
border: 1px solid #e5e5e5;
border-radius: 3px;
margin: 10px;
float: right;
overflow: hidden;
/* 關於文字 */
font: normal 13px "Helvetica Neue", sans-serif;
line-height: 1.5;
text-align: center;
/* 關於顏色,背景 */
background-color: #f5f5f5;
color: #fff;
opacity: .8;
/*其餘 */
cursor: pointer;
}
複製代碼
變量,混合,容許咱們單獨定義一系列通用的樣式,而後在須要的時候去調用。因此一些公共的樣式規則能夠單獨在一個less文件中定義,其餘地方調用,在作全局樣式調整時能很方便的修改
// LESS
@color: #4D926F;
#header {
color: @color;
}
h2 {
color: @color;
}
/* 生成的 CSS */
#header {
color: #4D926F;
}
h2 {
color: #4D926F;
}
//LESS
.bordered {
border-top: dotted 1px black;
border-bottom: solid 2px black;
}
#menu a {
color: #111;
.bordered;
}
.post a {
color: red;
.bordered;
}
/* 生成的 CSS */
#menu a {
color: #111;
border-top: dotted 1px black;
border-bottom: solid 2px black;
}
.post a {
color: red;
border-top: dotted 1px black;
border-bottom: solid 2px black;
}
複製代碼
將嵌套深度限制在2-3級。對於超過3級的嵌套,給予從新評估。這能夠避免出現過於詳實的CSS選擇器。 避免大量的嵌套規則。當可讀性受到影響時,將之打斷。推薦避免出現多於20行的嵌套規則出現。
#header {
color: black;
.navigation {
font-size: 12px;
}
.logo {
width: 300px;
&:hover { text-decoration: none }
}
}
複製代碼
有時候,你可能爲了更好組織CSS或者單純是爲了更好的封裝,將一些變量或者混合模塊打包起來, 你能夠像下面這樣在#bundle中定義一些屬性集以後能夠重複使用:
#bundle {
.button () {
display: block;
border: 1px solid black;
background-color: grey;
&:hover { background-color: white }
}
.tab { ... }
.citation { ... }
}
/*你只須要在 #header a中像這樣引入 .button:*/
#header a {
color: orange;
#bundle > .button;
}
複製代碼
以上HTML和CSS的規範大部分參考github上的frontend-guidelines及編碼規範by@mdo(後面幾個本身新增
javascript規範使用的是Standard標準,其好處可點擊超連接查看,npm,github等都是使用的此標準。 下文copy的Standard Style的具體規則,配合eslint使用
function hello (name) {
console.log('hi', name)
}
複製代碼
console.log('hello there')
$("<div class='box'>")
複製代碼
function myFunction () {
var result = something() // ✗ avoid
}
複製代碼
if (condition) { ... } // ✓ ok
if(condition) { ... } // ✗ avoid
複製代碼
function name (arg) { ... } // ✓ ok
function name(arg) { ... } // ✗ avoid
run(function () { ... }) // ✓ ok
run(function() { ... }) // ✗ avoid
複製代碼
if (name === 'John') // ✓ ok
if (name == 'John') // ✗ avoid
複製代碼
if (name !== 'John') // ✓ ok
if (name != 'John') // ✗ avoid
複製代碼
// ✓ ok
var x = 2
var message = 'hello, ' + name + '!'
// ✗ avoid
var x=2
var message = 'hello, '+name+'!'
複製代碼
// ✓ ok
var list = [1, 2, 3, 4]
function greet (name, options) { ... }
// ✗ avoid
var list = [1,2,3,4]
function greet (name,options) { ... }
複製代碼
// ✓ ok
if (condition) {
// ...
} else {
// ...
}
複製代碼
// ✗ avoid
if (condition)
{
// ...
}
else
{
// ...
}
複製代碼
// ✓ ok
if (options.quiet !== true) console.log('done')
複製代碼
// ✓ ok
if (options.quiet !== true) {
console.log('done')
}
複製代碼
// ✗ avoid
if (options.quiet !== true)
console.log('done')
複製代碼
// ✓ ok
run(function (err) {
if (err) throw err
window.alert('done')
})
複製代碼
// ✗ avoid
run(function (err) {
window.alert('done')
})
複製代碼
window.alert('hi') // ✓ ok
複製代碼
// ✓ ok
var value = 'hello world'
console.log(value)
複製代碼
// ✗ avoid
var value = 'hello world'
console.log(value)
複製代碼
// ✓ 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'
複製代碼
// ✓ ok
var silent = true
var verbose = true
複製代碼
// ✗ avoid
var silent = true, verbose = true
// ✗ avoid
var silent = true,
verbose = true
複製代碼
// ✓ ok
while ((m = text.match(expr))) {
// ...
}
// ✗ avoid
while (m = text.match(expr)) {
// ...
}
複製代碼
function foo () {return true} // ✗ avoid
function foo () { return true } // ✓ ok
複製代碼
function my_function () { } // ✗ avoid
function myFunction () { } // ✓ ok
var my_var = 'hello' // ✗ avoid
var myVar = 'hello' // ✓ ok
複製代碼
var obj = {
message: 'hello', // ✗ avoid
}
複製代碼
var obj = {
foo: 'foo'
,bar: 'bar' // ✗ avoid
}
var obj = {
foo: 'foo',
bar: 'bar' // ✓ ok
}
複製代碼
console.log ('hello') // ✗ avoid
console.log('hello') // ✓ ok
複製代碼
var obj = { 'key' : 'value' } // ✗ avoid
var obj = { 'key' :'value' } // ✗ avoid
var obj = { 'key':'value' } // ✗ avoid
複製代碼
var obj = { 'key': 'value' } // ✓ ok
複製代碼
function animal () {}
var dog = new animal() // ✗ avoid
複製代碼
function Animal () {}
var dog = new Animal() // ✓ ok
複製代碼
function Animal () {}
var dog = new Animal // ✗ avoid
var dog = new Animal() // ✓ ok
複製代碼
var person = {
set name (value) { // ✗ avoid
this.name = value
}
}
複製代碼
var person = {
set name (value) {
this.name = value
},
get name () { // ✓ ok
return this.name
}
}
複製代碼
class Dog {
constructor () {
super() // ✗ avoid
}
}
class Dog extends Mammal {
constructor () {
super() // ✓ ok
}
}
複製代碼
var nums = new Array(1, 2, 3) // ✗ avoid
var nums = [1, 2, 3] // ✓ ok
複製代碼
function foo (n) {
if (n <= 0) return
arguments.callee(n - 1) // ✗ avoid
}
function foo (n) {
if (n <= 0) return
foo(n - 1)
}
複製代碼
class Dog {}
Dog = 'Fido' // ✗ avoid
複製代碼
const score = 100
score = 125 // ✗ avoid
複製代碼
if (false) { // ✗ avoid
// ...
}
if (x === 0) { // ✓ ok
// ...
}
while (true) { // ✓ ok
// ...
}
複製代碼
var pattern = /\x1f/ // ✗ avoid
var pattern = /\x20/ // ✓ ok
複製代碼
function sum (a, b) {
debugger // ✗ avoid
return a + b
}
複製代碼
var name
delete name // ✗ avoid
複製代碼
function sum (a, b, a) { // ✗ avoid
// ...
}
function sum (a, b, c) { // ✓ ok
// ...
}
複製代碼
class Dog {
bark () {}
bark () {} // ✗ avoid
}
複製代碼
var user = {
name: 'Jane Doe',
name: 'John Doe' // ✗ avoid
}
複製代碼
switch (id) {
case 1:
// ...
case 1: // ✗ avoid
}
複製代碼
import { myFunc1 } from 'module'
import { myFunc2 } from 'module' // ✗ avoid
import { myFunc1, myFunc2 } from 'module' // ✓ ok
複製代碼
const myRegex = /^abc[]/ // ✗ avoid
const myRegex = /^abc[a-z]/ // ✓ ok
複製代碼
const { a: {} } = foo // ✗ avoid
const { a: { b } } = foo // ✓ ok
複製代碼
eval( "var result = user." + propName ) // ✗ avoid
var result = user[propName] // ✓ ok
複製代碼
try {
// ...
} catch (e) {
e = 'new value' // ✗ avoid
}
try {
// ...
} catch (e) {
const newVal = 'new value' // ✓ ok
}
複製代碼
Object.prototype.age = 21 // ✗ avoid
複製代碼
const name = function () {
getName()
}.bind(user) // ✗ avoid
const name = function () {
this.getName()
}.bind(user) // ✓ ok
複製代碼
const result = true
if (!!result) { // ✗ avoid
// ...
}
const result = true
if (result) { // ✓ ok
// ...
}
複製代碼
const myFunc = (function () { }) // ✗ avoid
const myFunc = function () { } // ✓ ok
複製代碼
switch (filter) {
case 1:
doSomething() // ✗ avoid
case 2:
doSomethingElse()
}
switch (filter) {
case 1:
doSomething()
break // ✓ ok
case 2:
doSomethingElse()
}
switch (filter) {
case 1:
doSomething()
// fallthrough // ✓ ok
case 2:
doSomethingElse()
}
複製代碼
const discount = .5 // ✗ avoid
const discount = 0.5 // ✓ ok
複製代碼
function myFunc () { }
myFunc = myOtherFunc // ✗ avoid
複製代碼
window = {} // ✗ avoid
複製代碼
setTimeout("alert('Hello world')") // ✗ avoid
setTimeout(function () { alert('Hello world') }) // ✓ ok
複製代碼
if (authenticated) {
function setAuthUser () {} // ✗ avoid
}
複製代碼
RegExp('[a-z') // ✗ avoid
RegExp('[a-z]') // ✓ ok
複製代碼
function myFunc () /*<NBSP>*/{} // ✗ avoid
複製代碼
Foo.prototype.__iterator__ = function () {} // ✗ avoid
複製代碼
var score = 100
function game () {
score: 50 // ✗ avoid
}
複製代碼
label:
while (true) {
break label // ✗ avoid
}
複製代碼
function myFunc () {
{ // ✗ avoid
myOtherFunc()
}
}
function myFunc () {
myOtherFunc() // ✓ ok
}
複製代碼
const id = 1234 // ✗ avoid
const id = 1234 // ✓ ok
複製代碼
const message = 'Hello \ world' // ✗ avoid
複製代碼
new Character() // ✗ avoid
const character = new Character() // ✓ ok
複製代碼
var sum = new Function('a', 'b', 'return a + b') // ✗ avoid
複製代碼
let config = new Object() // ✗ avoid
複製代碼
const myModule = new require('my-module') // ✗ avoid
複製代碼
const foo = new Symbol('foo') // ✗ avoid
複製代碼
const message = new String('hello') // ✗ avoid
複製代碼
const math = Math() // ✗ avoid
複製代碼
const num = 042 // ✗ avoid
const num = '042' // ✓ ok
複製代碼
const copyright = 'Copyright \251' // ✗ avoid
複製代碼
const pathToFile = __dirname + '/app.js' // ✗ avoid
const pathToFile = path.join(__dirname, 'app.js') // ✓ ok
複製代碼
const foo = obj.__proto__ // ✗ avoid
const foo = Object.getPrototypeOf(obj) // ✓ ok
複製代碼
let name = 'John'
let name = 'Jane' // ✗ avoid
let name = 'John'
name = 'Jane' // ✓ ok
複製代碼
const regexp = /test value/ // ✗ avoid
const regexp = /test {3}value/ // ✓ ok
const regexp = /test value/ // ✓ ok
複製代碼
function sum (a, b) {
return result = a + b // ✗ avoid
}
function sum (a, b) {
return (result = a + b) // ✓ ok
}
複製代碼
name = name // ✗ avoid
複製代碼
if (score === score) {} // ✗ avoid
複製代碼
if (doSomething(), !!test) {} // ✗ avoid
複製代碼
let undefined = 'value' // ✗ avoid
複製代碼
let fruits = ['apple',, 'orange'] // ✗ avoid
複製代碼
const message = 'Hello ${name}' // ✗ avoid
const message = `Hello ${name}` // ✓ ok
複製代碼
class Dog extends Animal {
constructor () {
this.legs = 4 // ✗ avoid
super()
}
}
複製代碼
throw 'error' // ✗ avoid
throw new Error('error') // ✓ ok
複製代碼
let name = undefined // ✗ avoid
let name
name = 'value' // ✓ ok
複製代碼
for (let i = 0; i < items.length; j++) {...} // ✗ avoid
for (let i = 0; i < items.length; i++) {...} // ✓ ok
複製代碼
let score = val ? val : 0 // ✗ avoid
let score = val || 0 // ✓ ok
複製代碼
function doSomething () {
return true
console.log('never called') // ✗ avoid
}
複製代碼
try {
// ...
} catch (e) {
// ...
} finally {
return 42 // ✗ avoid
}
複製代碼
if (!key in obj) {} // ✗ avoid
複製代碼
sum.call(null, 1, 2, 3) // ✗ avoid
複製代碼
const user = { ['name']: 'John Doe' } // ✗ avoid
const user = { name: 'John Doe' } // ✓ ok
複製代碼
class Car {
constructor () { // ✗ avoid
}
}
複製代碼
let message = 'Hell\o' // ✗ avoid
複製代碼
import { config as config } from './config' // ✗ avoid
import { config } from './config' // ✓ ok
複製代碼
user .name // ✗ avoid
user.name // ✓ ok
複製代碼
with (val) {...} // ✗ avoid
複製代碼
const user = {
name: 'Jane Doe', age: 30,
username: 'jdoe86' // ✗ avoid
}
const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } // ✓ ok
const user = {
name: 'Jane Doe',
age: 30,
username: 'jdoe86'
}
複製代碼
if (user) {
// ✗ avoid
const name = getName()
}
if (user) {
const name = getName() // ✓ ok
}
複製代碼
fn(... args) // ✗ avoid
fn(...args) // ✓ ok
複製代碼
for (let i = 0 ;i < items.length ;i++) {...} // ✗ avoid
for (let i = 0; i < items.length; i++) {...} // ✓ ok
複製代碼
if (admin){...} // ✗ avoid
if (admin) {...} // ✓ ok
複製代碼
getName( name ) // ✗ avoid
getName(name) // ✓ ok
複製代碼
typeof!admin // ✗ avoid
typeof !admin // ✓ ok
複製代碼
//comment // ✗ avoid
// comment // ✓ ok
/*comment*/ // ✗ avoid
/* comment */ // ✓ ok
複製代碼
const message = `Hello, ${ name }` // ✗ avoid
const message = `Hello, ${name}` // ✓ ok
複製代碼
if (price === NaN) { } // ✗ avoid
if (isNaN(price)) { } // ✓ ok
複製代碼
typeof name === 'undefimed' // ✗ avoid
typeof name === 'undefined' // ✓ ok
複製代碼
const getName = function () { }() // ✗ avoid
const getName = (function () { }()) // ✓ ok
const getName = (function () { })() // ✓ ok
複製代碼
yield* increment() // ✗ avoid
yield * increment() // ✓ ok
複製代碼
if (42 === age) { } // ✗ avoid
if (age === 42) { } // ✓ ok
複製代碼
window.alert('hi') // ✗ avoid
window.alert('hi'); // ✓ ok
複製代碼
** eslint: no-unexpected-multiline **
// ✓ ok
;(function () {
window.alert('ok')
}())
// ✗ avoid
(function () {
window.alert('ok')
}())
複製代碼
// ✓ ok
;[1, 2, 3].forEach(bar)
// ✗ avoid
[1, 2, 3].forEach(bar)
複製代碼
// ✓ ok
;`hello`.indexOf('o')
// ✗ avoid
`hello`.indexOf('o')
複製代碼
備註:上面的寫法只能說聰明過頭了。
相比更加可讀易懂的代碼,那些看似投巧的寫法是不可取的。
譬如:
;[1, 2, 3].forEach(bar)
複製代碼
建議的寫法是:
var nums = [1, 2, 3]
nums.forEach(bar)
複製代碼
ES6 提出了兩個新的聲明變量的命令:let和const。其中,let徹底能夠取代var,由於二者語義相同,並且let沒有反作用。
在全局環境,不該該設置變量,只應設置常量
好處:
const
優於let
有幾個緣由。一個是const
能夠提醒閱讀程序的人,這個變量不該該改變;另外一個是const
比較符合函數式編程思想,運算不改變值,只是新建值,並且這樣也有利於未來的分佈式運算;最後一個緣由是 JavaScript 編譯器會對const
進行優化,因此多使用const
,有利於提升程序的運行效率,也就是說let
和const
的本質區別,實際上是編譯器內部的處理不一樣。 const聲明常量還有兩個好處,一是閱讀代碼的人馬上會意識到不該該修改這個值,二是防止了無心間修改變量值所致使的錯誤。
使用數組成員對變量賦值時,優先使用解構賦值。
const arr = [1, 2, 3, 4];
// bad
const first = arr[0];
const second = arr[1];
// good
const [first, second] = arr;
複製代碼
函數的參數若是是對象的成員,優先使用解構賦值。
// bad
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
}
// good
function getFullName(obj) {
const { firstName, lastName } = obj;
}
// best
function getFullName({ firstName, lastName }) {
}
複製代碼
若是函數返回多個值,優先使用對象的解構賦值,而不是數組的解構賦值。這樣便於之後添加返回值,以及更改返回值的順序。
// bad
function processInput(input) {
return [left, right, top, bottom];
}
// good
function processInput(input) {
return { left, right, top, bottom };
}
const { left, right } = processInput(input);
複製代碼
對象儘可能靜態化,一旦定義,就不得隨意添加新的屬性。若是添加屬性不可避免,要使用Object.assign方法。
// bad
const a = {};
a.x = 3;
// if reshape unavoidable
const a = {};
Object.assign(a, { x: 3 });
// good
const a = { x: null };
a.x = 3;
複製代碼
若是對象的屬性名是動態的,能夠在創造對象的時候,使用屬性表達式定義。
// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
複製代碼
另外,對象的屬性和方法,儘可能採用簡潔表達法,這樣易於描述和書寫。
var ref = 'some value';
// bad
const atom = {
ref: ref,
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
ref,
value: 1,
addValue(value) {
return atom.value + value;
},
};
複製代碼
使用擴展運算符(...)拷貝數組。
// bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items];
複製代碼
使用 Array.from 方法,將相似數組的對象轉爲數組。
const foo = document.querySelectorAll('.foo');
const nodes = Array.from(foo);
複製代碼
當即執行函數能夠寫成箭頭函數的形式。
(() => {
console.log('Welcome to the Internet.');
})();
複製代碼
那些須要使用函數表達式的場合,儘可能用箭頭函數代替。由於這樣更簡潔,並且綁定了 this。
// bad
[1, 2, 3].map(function (x) {
return x * x;
});
// good
[1, 2, 3].map((x) => {
return x * x;
});
// best
[1, 2, 3].map(x => x * x);
複製代碼
簡單的、單行的、不會複用的函數,建議採用箭頭函數。若是函數體較爲複雜,行數較多,仍是應該採用傳統的函數寫法。
注意區分 Object 和 Map,只有模擬現實世界的實體對象時,才使用 Object。若是隻是須要key: value的數據結構,使用 Map 結構。由於 Map 有內建的遍歷機制。
let map = new Map(arr);
for (let key of map.keys()) {
console.log(key);
}
for (let value of map.values()) {
console.log(value);
}
for (let item of map.entries()) {
console.log(item[0], item[1]);
}
複製代碼
老是用 Class,取代須要 prototype 的操做。由於 Class 的寫法更簡潔,更易於理解。
// 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;
}
}
複製代碼
使用extends實現繼承,由於這樣更簡單,不會有破壞instanceof運算的危險。
// bad
const inherits = require('inherits');
function PeekableQueue(contents) {
Queue.apply(this, contents);
}
inherits(PeekableQueue, Queue);
PeekableQueue.prototype.peek = function() {
return this._queue[0];
}
// good
class PeekableQueue extends Queue {
peek() {
return this._queue[0];
}
}
複製代碼
通常來講,不要在then方法裏面定義失敗狀態的回調函數(即then的第二個參數),老是使用catch方法
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});
複製代碼
儘可能不要使用i++,儘可能使用i+=1;(除了for循環)
1.1 components
1.2 props
1.3 data
1.4 created
1.5 mounted
1.6 activited
1.7 update
1.8 beforeRouteUpdate
1.9 metods
1.10 filter
1.11 computed
1.12 watch
2.1 動賓短語(good:jumpPage、openCarInfoDialog)(bad:go、nextPage、show、open、login)
2.2 ajax 方法以 get、post 開頭,以 data 結尾(good:getListData、postFormData)(bad:takeData、confirmData、getList、postForm)
2.3 事件方法以 on 開頭(onTypeChange、onUsernameInput)
2.4 init、refresh 單詞除外
2.5 儘可能使用經常使用單詞開頭(set、get、open、close、jump)
2.6 駝峯命名(good: getListData)(bad: get_list_data、getlistData)
3.1 不在 mounted、created 之類的方法寫邏輯,取 ajax 數據,
3.2 在 created 裏面監聽 Bus 事件
原則:每個vue組件首先必須專一於解決一個單一的問題,獨立的,可複用的,微小的和可測試的。 若是你的組件作了太多的事或是變得臃腫,請將其拆成更小的組件並保持單一的原則。
<!-- 推薦 -->
<app-header></app-header>
<user-list></user-list>
<range-slider></range-slider>
<!-- 避免 -->
<btn-group></btn-group> <!-- 雖然簡短可是可讀性差. 使用 `button-group` 替代 -->
<ui-slider></ui-slider> <!-- ui 前綴太過於寬泛,在這裏意義不明確 -->
<slider></slider> <!-- 與自定義元素規範不兼容 -->
複製代碼
<template>
<input type="range" v-model="value" :max="max" :min="min">
</template>
<script type="text/javascript"> export default { props: { max: { type: Number, // 這裏添加了數字類型的校驗 default() { return 10; }, }, min: { type: Number, default() { return 0; }, }, value: { type: Number, default() { return 4; }, }, }, }; </script>
複製代碼
Vue.js 是一個基於組件的框架。若是你不知道什麼時候建立組件可能會致使如下問題:
首先,儘量早地嘗試構建出諸如模態框、提示框、工具條、菜單、頭部等這些明顯的(通用型)組件。總之,你知道的這些組件之後必定會在當前頁面或者是全局範圍內須要。
第二,在每個新的開發項目中,對於一整個頁面或者其中的一部分,在進行開發前先嚐試思考一下。若是你認爲它有一部分應該是一個組件,那麼就建立它吧。
最後,若是你不肯定,那就不要。避免那些「之後可能會有用」的組件污染你的項目。它們可能會永遠的只是(靜靜地)待在那裏,這一點也不聰明。注意,一旦你意識到應該這麼作,最好是就把它打破,以免與項目的其餘部分構成兼容性和複雜性。
// this is comment
複製代碼
/* */
複製代碼
// bad
/* start end */
// good
/* here is line 1 here is line 2 */
複製代碼
// 初始化value變量爲0
var value = 0;
複製代碼
// TODO 未處理IE6-8的兼容性
function setOpacity(node, val) {
node.style.opacity = val;
}
複製代碼
文檔註釋將會以預約格式出如今API文檔中。它以「/**」開頭,以「/」結束,其間的每一行均以「」開頭(均與開始符的第一個「」對齊),且註釋內容與「」間留一個空格。
/** * 模塊說明 * @module 模塊名 */
/** * Core模塊提供最基礎、最核心的接口 * @module Core */
複製代碼
/** * 類說明 * @class 類名 * @constructor */
複製代碼
@class必須搭配@constructor或@static使用,分別標記非靜態類與靜態類。
/** * 節點集合類 * @class NodeList * @constructor * @param {ArrayLike<Element>} nodes 初始化節點 */
複製代碼
/** * 方法說明 * @method 方法名 * @for 所屬類名 * @param {參數類型} 參數名 參數說明 * @return {返回值類型} 返回值說明 */
複製代碼
沒有指定@for時,表示此函數爲全局或模塊頂層函數。當函數爲靜態函數時,必須添加@static;當函數有參數時,必須使用@param;當函數有返回值時,必須使用@return。
/** * 返回當前集合中指定位置的元素 * @method * @for NodeList * @param {Number} [i=0] 位置下標。若是爲負數,則從集合的最後一個元素開始倒數 * @return {Element} 指定元素 */
- @param。聲明函數參數,必須與@method搭配使用。
- 當參數出現如下狀況時,使用對應的格式:[參數名]
- 參數有默認值 [參數名 = 默認值]
複製代碼
/** * 屬性說明 * @property {屬性類型} 屬性名 */
複製代碼