javascript代碼風(fēng)格
來源:https://github.com/airbnb/javascript
Objects 對(duì)象javascript// bad var item = new Object(); // good var item = {}; //不要使用保留字作為對(duì)象屬性,IE8不支持。 // bad var superman = { default: { clark: "kent" }, private: true }; // good var superman = { defaults: { clark: "kent" }, hidden: true };Arrays 數(shù)組
javascript// bad var items = new Array(); // good var items = []; //使用push添加數(shù)組元素 var someStack = []; // bad someStack[someStack.length] = "abracadabra"; // good someStack.push("abracadabra"); //復(fù)制數(shù)組的最快方法 var len = items.length; var itemsCopy = []; var i; // bad for (i = 0; i < len; i++) { itemsCopy[i] = items[i]; } // good itemsCopy = items.slice(); //轉(zhuǎn)換array-like object(如:{1:"xx",2:"yy",length:2}) 成數(shù)組 var args = Array.prototype.slice.call(arguments);Strings 字符串
javascript//使用單引號(hào) // bad var name = "Bob Parr"; // good var name = "Bob Parr"; // bad var fullName = "Bob " + this.lastName; // good var fullName = "Bob " + this.lastName; // 使用`+`進(jìn)行換行 var 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."; //拼接帶標(biāo)簽內(nèi)容時(shí),標(biāo)簽頭尾寫一起 // bad function inbox(messages) { items = "Functions 函數(shù)"; for (i = 0; i < length; i++) { items += "
"; } // good function inbox(messages) { items = []; for (i = 0; i < length; i++) { items[i] = "- " + messages[i].message + "
"; } return items + "" + messages[i].message + " "; } return "" + items.join("") + "
"; }
javascript// 使用自執(zhí)行函數(shù) // immediately-invoked function expression (IIFE) (function() { console.log("Welcome to the Internet. Please follow me."); })(); //型參別用`arguments` // bad function nope(name, options, arguments) { // ...stuff... } // good function yup(name, options, args) { // ...stuff... }Properties屬性
javascriptVariables 變量
var luke = { jedi: true, age: 28 }; // bad var isJedi = luke["jedi"]; //一般情況使用`.`調(diào)用, // good var isJedi = luke.jedi; function getProp(prop) { //屬性是變量,使用`[]`調(diào)用 return luke[prop]; } var isJedi = getProp("jedi");
javascriptEquality 比較操作
//使用var聲明變量 // bad superPower = new SuperPower(); // good var superPower = new SuperPower(); //不用`,`分割變量 // bad // (compare to above, and try to spot the mistake) var items = getItems(), goSportsTeam = true; dragonball = "z"; // good var items = getItems(); var goSportsTeam = true; var dragonball = "z"; //聲明未賦值變量在后面 // bad var i; var items = getItems(); var dragonball; var goSportsTeam = true; var len; // good var items = getItems(); var goSportsTeam = true; var dragonball; var length; var i; //函數(shù)內(nèi)變量聲明定義盡量放最前面,除非有函數(shù)開始有判斷`return false`, // bad function() { test(); console.log("doing stuff.."); //..other stuff.. var name = getName(); if (name === "test") { return false; } return name; } // good function() { var name = getName(); test(); console.log("doing stuff.."); //..other stuff.. if (name === "test") { return false; } return name; } // bad function() { var name = getName(); if (!arguments.length) { return false; } return true; } // good function() { if (!arguments.length) { return false; } var name = getName(); return true; }
javascript// bad if (name !== "") { // ...stuff... } // good if (name) { // ...stuff... } // bad if (collection.length > 0) { // ...stuff... } // good if (collection.length) { // ...stuff... }Blocks 塊
javascript// bad if (test) return false; // good if (test) return false; // good if (test) { return false; } // bad function() { return false; } // good function() { return false; }Comments 注釋
javascript// bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @return {Element} element function make(tag) { // ...stuff... return element; } // good /** * make() returns a new element * based on the passed in tag name * * @param {String} tag * @return {Element} element */ function make(tag) { // ...stuff... return element; } // bad var active = true; // is current tab //注釋在在代碼上方好 // good // is current tab var active = true; // bad function getType() { console.log("fetching type..."); // set the default type to "no type" var type = this._type || "no type"; return type; } // good function getType() { console.log("fetching type..."); //注釋上方要留一行空行 // set the default type to "no type" var type = this._type || "no type"; return type; }Type Casting 格式轉(zhuǎn)換
javascript// => this.reviewScore = 9; // bad var totalScore = this.reviewScore + ""; // good var totalScore = "" + this.reviewScore; // bad var totalScore = "" + this.reviewScore + " total score"; // good var totalScore = this.reviewScore + " total score"; var inputValue = "4"; // bad var val = new Number(inputValue); // bad var val = +inputValue; // bad var val = inputValue >> 0; // bad var val = parseInt(inputValue); // good var val = Number(inputValue); // good var val = parseInt(inputValue, 10); // good /** * parseInt was the reason my code was slow. * Bitshifting the String to coerce it to a * Number made it a lot faster. * 通過位移的方式轉(zhuǎn)換成數(shù)字,速度會(huì)快些 */ var val = inputValue >> 0; var age = 0; // bad var hasAge = new Boolean(age); // good var hasAge = Boolean(age); // good var hasAge = !!age;Naming Conventions 命名約定
javascript// bad function q() { // ...stuff... } //名字要有語意 // good function query() { // ..stuff.. } // bad var OBJEcttsssss = {}; var this_is_my_object = {}; //駝峰命名 // good var thisIsMyObject = {}; function thisIsMyFunction() {} // bad function user(options) { this.name = options.name; } //構(gòu)造函數(shù)大寫 // good function User(options) { this.name = options.name; } // bad this.__firstName__ = "Panda"; this.firstName_ = "Panda"; //私有屬性用`_`開頭 // good this._firstName = "Panda"; // bad function() { var self = this; return function() { console.log(self); }; } // bad function() { var that = this; return function() { console.log(that); }; } //保存調(diào)用者`this`為`_this` // good function() { var _this = this; return function() { console.log(_this); }; }Constructors 構(gòu)造函數(shù)
javascriptfunction Jedi() { console.log("new jedi"); } // bad Jedi.prototype = { fight: function fight() { console.log("fighting"); } }; // good Jedi.prototype.fight = function fight() { console.log("fighting"); };Events 事件
javascript// bad $(this).trigger("listingUpdated", listing.id); ... $(this).on("listingUpdated", function(e, listingId) { // do something with listingId }); //傳遞id時(shí)用對(duì)象包裹后再傳 // good $(this).trigger("listingUpdated", { listingId : listing.id }); ... $(this).on("listingUpdated", function(e, data) { // do something with data.listingId });Modules 模塊
說明文件路徑
文件名使用駝峰命名
開頭加上一個(gè) `!
模塊中使用"use strict"嚴(yán)格模式
使用noConflict()無沖突的輸出
javascript// fancyInput/fancyInput.js !function(global) { "use strict"; var previousFancyInput = global.FancyInput; function FancyInput(options) { this.options = options || {}; } FancyInput.noConflict = function noConflict() { global.FancyInput = previousFancyInput; return FancyInput; }; global.FancyInput = FancyInput; }(this);
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/85614.html
云極(EPC)是UCloud提供的高性能計(jì)算產(chǎn)品,為用戶提供基于公有云技術(shù)的超高性能算力以及涵蓋數(shù)據(jù)傳輸、數(shù)據(jù)計(jì)算、數(shù)據(jù)可視化等一站式的使用體驗(yàn)。EPC支持以下功能:-秒級(jí)創(chuàng)建計(jì)算節(jié)點(diǎn),按需計(jì)費(fèi),關(guān)機(jī)不收費(fèi)-支持開箱即用的應(yīng)用鏡像-贈(zèng)送1000GB共享存儲(chǔ),支持FTP文件上傳和下載功能,帶寬最高可達(dá)100Mb-可掛載虛擬的Nvidia Tesla T4 GPU, 為圖形處理功能加速-支持8- 24...
摘要:點(diǎn)擊查看原文總結(jié)一下變量名函數(shù)名用駝峰,以小寫字母開頭逗號(hào)和操作符之后要有空格縮進(jìn)為個(gè)空格其實(shí)現(xiàn)在有很多是個(gè)的語句的結(jié)尾有分號(hào)復(fù)合語句左花括號(hào)在首行末尾,且之前有空格右花括號(hào)另起一行,之前沒有空格結(jié)尾沒有括號(hào)對(duì)象左花括號(hào)不換行,之前有空格 點(diǎn)擊查看原文 總結(jié)一下: 變量名函數(shù)名用駝峰,以小寫字母開頭 逗號(hào)和操作符之后要有空格 縮進(jìn)為4個(gè)空格(其實(shí)現(xiàn)在有很多是2個(gè)的 nodejs ...
摘要:在遍歷的時(shí)候很容易犯這樣的錯(cuò)誤這是一個(gè)無限循環(huán),因?yàn)槭莿?dòng)態(tài)的實(shí)時(shí)更新的。應(yīng)該把屬性初始化第二個(gè)變量應(yīng)該盡量減少訪問的次數(shù)因?yàn)槊看卧L問都會(huì)運(yùn)行依次基于文檔的查詢所以應(yīng)該考慮將從中提取出的值緩存起來。 動(dòng)態(tài)腳本 插入外部腳本文件 以script元素為例: 使用DOM動(dòng)態(tài)的創(chuàng)建出這個(gè)元素: function loadScript(url) { var script = docum...
摘要:測試動(dòng)態(tài)加載到標(biāo)簽并執(zhí)行回調(diào)方法調(diào)用加載成功動(dòng)態(tài)加載腳本地址回調(diào)函數(shù)加載樣式站中下載打開方法測試頁面跳轉(zhuǎn)到微信中不能打開其他安卓手機(jī)嘗試調(diào)用未指定需要打開的可參考自定義協(xié)議參數(shù)轉(zhuǎn)換參考參數(shù)轉(zhuǎn)對(duì)象使用對(duì)象轉(zhuǎn)參數(shù) js實(shí)用方法記錄-動(dòng)態(tài)加載css/js 1.動(dòng)態(tài)加載js文件到head標(biāo)簽并執(zhí)行回調(diào)方法調(diào)用:dynamicLoadJs(http://www.yimo.link/static/...
摘要:測試動(dòng)態(tài)加載到標(biāo)簽并執(zhí)行回調(diào)方法調(diào)用加載成功動(dòng)態(tài)加載腳本地址回調(diào)函數(shù)加載樣式站中下載打開方法測試頁面跳轉(zhuǎn)到微信中不能打開其他安卓手機(jī)嘗試調(diào)用未指定需要打開的可參考自定義協(xié)議參數(shù)轉(zhuǎn)換參考參數(shù)轉(zhuǎn)對(duì)象使用對(duì)象轉(zhuǎn)參數(shù) js實(shí)用方法記錄-動(dòng)態(tài)加載css/js 1.動(dòng)態(tài)加載js文件到head標(biāo)簽并執(zhí)行回調(diào)方法調(diào)用:dynamicLoadJs(http://www.yimo.link/static/...
摘要:測試動(dòng)態(tài)加載到標(biāo)簽并執(zhí)行回調(diào)方法調(diào)用加載成功動(dòng)態(tài)加載腳本地址回調(diào)函數(shù)加載樣式站中下載打開方法測試頁面跳轉(zhuǎn)到微信中不能打開其他安卓手機(jī)嘗試調(diào)用未指定需要打開的可參考自定義協(xié)議參數(shù)轉(zhuǎn)換參考參數(shù)轉(zhuǎn)對(duì)象使用對(duì)象轉(zhuǎn)參數(shù) js實(shí)用方法記錄-動(dòng)態(tài)加載css/js 1.動(dòng)態(tài)加載js文件到head標(biāo)簽并執(zhí)行回調(diào)方法調(diào)用:dynamicLoadJs(http://www.yimo.link/static/...
閱讀 2652·2021-11-23 09:51
閱讀 2571·2021-09-30 09:48
閱讀 1166·2021-09-10 10:51
閱讀 2288·2021-08-12 13:22
閱讀 3642·2021-08-11 10:24
閱讀 2245·2019-08-30 15:55
閱讀 709·2019-08-30 14:05
閱讀 3268·2019-08-30 13:03