javascript代碼風格
來源:https://github.com/airbnb/javascript
Objects 對象javascript// bad var item = new Object(); // good var item = {}; //不要使用保留字作為對象屬性,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//使用單引號 // bad var name = "Bob Parr"; // good var name = "Bob Parr"; // bad var fullName = "Bob " + this.lastName; // good var fullName = "Bob " + this.lastName; // 使用`+`進行換行 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."; //拼接帶標簽內(nèi)容時,標簽頭尾寫一起 // 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ù)字,速度會快些 */ 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時用對象包裹后再傳 // good $(this).trigger("listingUpdated", { listingId : listing.id }); ... $(this).on("listingUpdated", function(e, data) { // do something with data.listingId });Modules 模塊
說明文件路徑
文件名使用駝峰命名
開頭加上一個 `!
模塊中使用"use strict"嚴格模式
使用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)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/85614.html
云極(EPC)是UCloud提供的高性能計算產(chǎn)品,為用戶提供基于公有云技術(shù)的超高性能算力以及涵蓋數(shù)據(jù)傳輸、數(shù)據(jù)計算、數(shù)據(jù)可視化等一站式的使用體驗。EPC支持以下功能:-秒級創(chuàng)建計算節(jié)點,按需計費,關(guān)機不收費-支持開箱即用的應(yīng)用鏡像-贈送1000GB共享存儲,支持FTP文件上傳和下載功能,帶寬最高可達100Mb-可掛載虛擬的Nvidia Tesla T4 GPU, 為圖形處理功能加速-支持8- 24...
摘要:點擊查看原文總結(jié)一下變量名函數(shù)名用駝峰,以小寫字母開頭逗號和操作符之后要有空格縮進為個空格其實現(xiàn)在有很多是個的語句的結(jié)尾有分號復(fù)合語句左花括號在首行末尾,且之前有空格右花括號另起一行,之前沒有空格結(jié)尾沒有括號對象左花括號不換行,之前有空格 點擊查看原文 總結(jié)一下: 變量名函數(shù)名用駝峰,以小寫字母開頭 逗號和操作符之后要有空格 縮進為4個空格(其實現(xiàn)在有很多是2個的 nodejs ...
摘要:在遍歷的時候很容易犯這樣的錯誤這是一個無限循環(huán),因為是動態(tài)的實時更新的。應(yīng)該把屬性初始化第二個變量應(yīng)該盡量減少訪問的次數(shù)因為每次訪問都會運行依次基于文檔的查詢所以應(yīng)該考慮將從中提取出的值緩存起來。 動態(tài)腳本 插入外部腳本文件 以script元素為例: 使用DOM動態(tài)的創(chuàng)建出這個元素: function loadScript(url) { var script = docum...
摘要:測試動態(tài)加載到標簽并執(zhí)行回調(diào)方法調(diào)用加載成功動態(tài)加載腳本地址回調(diào)函數(shù)加載樣式站中下載打開方法測試頁面跳轉(zhuǎn)到微信中不能打開其他安卓手機嘗試調(diào)用未指定需要打開的可參考自定義協(xié)議參數(shù)轉(zhuǎn)換參考參數(shù)轉(zhuǎn)對象使用對象轉(zhuǎn)參數(shù) js實用方法記錄-動態(tài)加載css/js 1.動態(tài)加載js文件到head標簽并執(zhí)行回調(diào)方法調(diào)用:dynamicLoadJs(http://www.yimo.link/static/...
摘要:測試動態(tài)加載到標簽并執(zhí)行回調(diào)方法調(diào)用加載成功動態(tài)加載腳本地址回調(diào)函數(shù)加載樣式站中下載打開方法測試頁面跳轉(zhuǎn)到微信中不能打開其他安卓手機嘗試調(diào)用未指定需要打開的可參考自定義協(xié)議參數(shù)轉(zhuǎn)換參考參數(shù)轉(zhuǎn)對象使用對象轉(zhuǎn)參數(shù) js實用方法記錄-動態(tài)加載css/js 1.動態(tài)加載js文件到head標簽并執(zhí)行回調(diào)方法調(diào)用:dynamicLoadJs(http://www.yimo.link/static/...
摘要:測試動態(tài)加載到標簽并執(zhí)行回調(diào)方法調(diào)用加載成功動態(tài)加載腳本地址回調(diào)函數(shù)加載樣式站中下載打開方法測試頁面跳轉(zhuǎn)到微信中不能打開其他安卓手機嘗試調(diào)用未指定需要打開的可參考自定義協(xié)議參數(shù)轉(zhuǎn)換參考參數(shù)轉(zhuǎn)對象使用對象轉(zhuǎn)參數(shù) js實用方法記錄-動態(tài)加載css/js 1.動態(tài)加載js文件到head標簽并執(zhí)行回調(diào)方法調(diào)用:dynamicLoadJs(http://www.yimo.link/static/...
閱讀 2581·2021-11-23 09:51
閱讀 2495·2021-09-30 09:48
閱讀 1094·2021-09-10 10:51
閱讀 2229·2021-08-12 13:22
閱讀 3583·2021-08-11 10:24
閱讀 2183·2019-08-30 15:55
閱讀 653·2019-08-30 14:05
閱讀 3220·2019-08-30 13:03