日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
如何寫(xiě)出優(yōu)雅的JS代碼,變量和函數(shù)的正確寫(xiě)法

在開(kāi)發(fā)中,變量名,函數(shù)名一般要做到清晰明了,盡量做到看名字就能讓人知道你的意圖,所以變量和函數(shù)命名是挺重要,今天來(lái)看看如果較優(yōu)雅的方式給變量和函數(shù)命名。

創(chuàng)新互聯(lián)自2013年創(chuàng)立以來(lái),是專(zhuān)業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站建設(shè)、網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元五家渠做網(wǎng)站,已為上家服務(wù),為五家渠各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220

一、變量

使用有意義和可發(fā)音的變量名

 
 
 
  1. // 不好的寫(xiě)法 
  2. const yyyymmdstr = moment().format("YYYY/MM/DD"); 
  3.  
  4. // 好的寫(xiě)法 
  5. const currentDate = moment().format("YYYY/MM/DD"); 

對(duì)同一類(lèi)型的變量使用相同的詞匯

 
 
 
  1. // 不好的寫(xiě)法 
  2. getUserInfo(); 
  3. getClientData(); 
  4. getCustomerRecord(); 
  5.  
  6. // 好的寫(xiě)法 
  7. getUser(); 

使用可搜索的名字

我們讀的會(huì)比我們寫(xiě)的多得多,所以如果命名太過(guò)隨意不僅會(huì)給后續(xù)的維護(hù)帶來(lái)困難,也會(huì)傷害了讀我們代碼的開(kāi)發(fā)者。讓你的變量名可被讀取,像 buddy.js 和 ESLint 這樣的工具可以幫助識(shí)別未命名的常量。

 
 
 
  1. // 不好的寫(xiě)法 
  2. // 86400000 的用途是什么? 
  3. setTimeout(blastOff, 86400000); 
  4.  
  5. // 好的寫(xiě)法 
  6. const MILLISECONDS_IN_A_DAY = 86_400_000; 
  7. setTimeout(blastOff, MILLISECONDS_IN_A_DAY); 

使用解釋性變量

 
 
 
  1. // 不好的寫(xiě)法 
  2. const address = "One Infinite Loop, Cupertino 95014"; 
  3. const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 
  4. saveCityZipCode( 
  5.   address.match(cityZipCodeRegex)[1], 
  6.   address.match(cityZipCodeRegex)[2] 
  7. ); 
  8.  
  9.  
  10. // 好的寫(xiě)法 
  11. const address = "One Infinite Loop, Cupertino 95014"; 
  12. const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 
  13. const [_, city, zipCode] = address.match(cityZipCodeRegex) || []; 
  14. saveCityZipCode(city, zipCode); 

避免費(fèi)腦的猜測(cè)

顯式用于隱式

 
 
 
  1. // 不好的寫(xiě)法 
  2. const locations = ["Austin", "New York", "San Francisco"]; 
  3. locations.forEach(l => { 
  4.   doStuff(); 
  5.   doSomeOtherStuff(); 
  6.   // ... 
  7.   // ... 
  8.   // ... 
  9.   // 等等,“l(fā)”又是什么? 
  10.   dispatch(l); 
  11.  
  12. // 好的寫(xiě)法 
  13. const locations = ["Austin", "New York", "San Francisco"]; 
  14. locations.forEach(location => { 
  15.   doStuff(); 
  16.   doSomeOtherStuff(); 
  17.   // ... 
  18.   // ... 
  19.   // ... 
  20.   dispatch(location); 
  21. }); 

無(wú)需添加不必要的上下文

如果類(lèi)名/對(duì)象名已經(jīng)說(shuō)明了,就無(wú)需在變量名中重復(fù)。

 
 
 
  1. // 不好的寫(xiě)法 
  2. const Car = { 
  3.   carMake: "Honda", 
  4.   carModel: "Accord", 
  5.   carColor: "Blue" 
  6. }; 
  7.  
  8. function paintCar(car) { 
  9.   car.carColor = "Red"; 
  10. // 好的寫(xiě)法 
  11. const Car = { 
  12.   make: "Honda", 
  13.   model: "Accord", 
  14.   color: "Blue" 
  15. }; 
  16.  
  17. function paintCar(car) { 
  18.   car.color = "Red"; 

使用默認(rèn)參數(shù)代替邏輯或(與)運(yùn)算

 
 
 
  1. // 不好的寫(xiě)法 
  2. function createMicrobrewery(name) { 
  3.   const breweryName = name || "Hipster Brew Co."; 
  4.   // ... 
  5. // 好的寫(xiě)法 
  6. function createMicrobrewery(name = "Hipster Brew Co.") { 
  7.   // ... 

二、函數(shù)

函數(shù)參數(shù)(理想情況下為2個(gè)或更少)

限制函數(shù)參數(shù)的數(shù)量是非常重要的,因?yàn)樗箿y(cè)試函數(shù)變得更容易。如果有三個(gè)以上的參數(shù),就會(huì)導(dǎo)致組合爆炸,必須用每個(gè)單獨(dú)的參數(shù)測(cè)試大量不同的情況。

一個(gè)或兩個(gè)參數(shù)是理想的情況,如果可能,應(yīng)避免三個(gè)參數(shù)。除此之外,還應(yīng)該合并。大多數(shù)情況下,大于三個(gè)參數(shù)可以用對(duì)象來(lái)代替。

 
 
 
  1. // 不好的寫(xiě)法 
  2. function createMenu(title, body, buttonText, cancellable) { 
  3.   // ... 
  4.  
  5. createMenu("Foo", "Bar", "Baz", true); 
  6.  
  7. // 好的寫(xiě)法 
  8. function createMenu({ title, body, buttonText, cancellable }) { 
  9.   // ... 
  10.  
  11. createMenu({ 
  12.   title: "Foo", 
  13.   body: "Bar", 
  14.   buttonText: "Baz", 
  15.   cancellable: true 
  16. }); 

函數(shù)應(yīng)該只做一件事

這是目前為止軟件工程中最重要的規(guī)則。當(dāng)函數(shù)做不止一件事時(shí),它們就更難組合、測(cè)試和推理。可以將一個(gè)函數(shù)隔離為一個(gè)操作時(shí),就可以很容易地重構(gòu)它,代碼也會(huì)讀起來(lái)更清晰。

 
 
 
  1. // 不好的寫(xiě)法 
  2. function emailClients(clients) { 
  3.   clients.forEach(client => { 
  4.     const clientRecord = database.lookup(client); 
  5.     if (clientRecord.isActive()) { 
  6.       email(client); 
  7.     } 
  8.   }); 
  9.  
  10. // 好的寫(xiě)法 
  11.  
  12. function emailActiveClients(clients) { 
  13.   clients.filter(isActiveClient).forEach(email); 
  14.  
  15. function isActiveClient(client) { 
  16.   const clientRecord = database.lookup(client); 
  17.   return clientRecord.isActive(); 

函數(shù)名稱(chēng)應(yīng)說(shuō)明其作用

 
 
 
  1. // 不好的寫(xiě)法 
  2. function addToDate(date, month) { 
  3.   // ... 
  4.  
  5. const date = new Date(); 
  6.  
  7. // 從函數(shù)名稱(chēng)很難知道添加什么 
  8. addToDate(date, 1); 
  9.  
  10. // 好的寫(xiě)法 
  11. function addMonthToDate(month, date) { 
  12.   // ... 
  13.  
  14. const date = new Date(); 
  15. addMonthToDate(1, date); 

函數(shù)應(yīng)該只有一個(gè)抽象層次

當(dāng)有一個(gè)以上的抽象層次函數(shù),意味該函數(shù)做得太多了,需要將函數(shù)拆分可以實(shí)現(xiàn)可重用性和更簡(jiǎn)單的測(cè)試。

 
 
 
  1. // 不好的寫(xiě)法 
  2. function parseBetterJSAlternative(code) { 
  3.   const REGEXES = [ 
  4.     // ... 
  5.   ]; 
  6.  
  7.   const statements = code.split(" "); 
  8.   const tokens = []; 
  9.   REGEXES.forEach(REGEX => { 
  10.     statements.forEach(statement => { 
  11.       // ... 
  12.     }); 
  13.   }); 
  14.  
  15.   const ast = []; 
  16.   tokens.forEach(token => { 
  17.     // lex... 
  18.   }); 
  19.  
  20.   ast.forEach(node => { 
  21.     // parse... 
  22.   }); 
  23.  
  24. // 好的寫(xiě)法 
  25. function parseBetterJSAlternative(code) { 
  26.   const tokens = tokenize(code); 
  27.   const syntaxTree = parse(tokens); 
  28.   syntaxTree.forEach(node => { 
  29.     // parse... 
  30.   }); 
  31.  
  32. function tokenize(code) { 
  33.   const REGEXES = [ 
  34.     // ... 
  35.   ]; 
  36.  
  37.   const statements = code.split(" "); 
  38.   const tokens = []; 
  39.   REGEXES.forEach(REGEX => { 
  40.     statements.forEach(statement => { 
  41.       tokens.push(/* ... */); 
  42.     }); 
  43.   }); 
  44.  
  45.   return tokens; 
  46.  
  47. function parse(tokens) { 
  48.   const syntaxTree = []; 
  49.   tokens.forEach(token => { 
  50.     syntaxTree.push(/* ... */); 
  51.   }); 
  52.  
  53.   return syntaxTree; 

刪除重復(fù)的代碼

盡量避免重復(fù)的代碼,重復(fù)的代碼是不好的,它意味著如果我們需要更改某些邏輯,要改很多地方。

通常,有重復(fù)的代碼,是因?yàn)橛袃蓚€(gè)或多個(gè)稍有不同的事物,它們有很多共同點(diǎn),但是它們之間的差異迫使我們編寫(xiě)兩個(gè)或多個(gè)獨(dú)立的函數(shù)來(lái)完成許多相同的事情。 刪除重復(fù)的代碼意味著創(chuàng)建一個(gè)僅用一個(gè)函數(shù)/模塊/類(lèi)就可以處理這組不同事物的抽象。

獲得正確的抽象是至關(guān)重要的,這就是為什么我們應(yīng)該遵循類(lèi)部分中列出的 「SOLID原則」。糟糕的抽象可能比重復(fù)的代碼更糟糕,所以要小心!說(shuō)了這么多,如果你能做一個(gè)好的抽象,那就去做吧!不要重復(fù)你自己,否則你會(huì)發(fā)現(xiàn)自己在任何時(shí)候想要改變一件事的時(shí)候都要更新多個(gè)地方。

「設(shè)計(jì)模式的六大原則有」

  • Single Responsibility Principle:?jiǎn)我宦氊?zé)原則
  • Open Closed Principle:開(kāi)閉原則
  • Liskov Substitution Principle:里氏替換原則
  • Law of Demeter:迪米特法則
  • Interface Segregation Principle:接口隔離原則
  • Dependence Inversion Principle:依賴倒置原則

把這六個(gè)原則的首字母聯(lián)合起來(lái)(兩個(gè) L 算做一個(gè))就是 SOLID (solid,穩(wěn)定的),其代表的含義就是這六個(gè)原則結(jié)合使用的好處:建立穩(wěn)定、靈活、健壯的設(shè)計(jì)。下面我們來(lái)分別看一下這六大設(shè)計(jì)原則。

「不好的寫(xiě)法」

 
 
 
  1. function showDeveloperList(developers) { 
  2.   developers.forEach(developer => { 
  3.     const expectedSalary = developer.calculateExpectedSalary(); 
  4.     const experience = developer.getExperience(); 
  5.     const githubLink = developer.getGithubLink(); 
  6.     const data = { 
  7.       expectedSalary, 
  8.       experience, 
  9.       githubLink 
  10.     }; 
  11.  
  12.     render(data); 
  13.   }); 
  14.  
  15. function showManagerList(managers) { 
  16.   managers.forEach(manager => { 
  17.     const expectedSalary = manager.calculateExpectedSalary(); 
  18.     const experience = manager.getExperience(); 
  19.     const portfolio = manager.getMBAProjects(); 
  20.     const data = { 
  21.       expectedSalary, 
  22.       experience, 
  23.       portfolio 
  24.     }; 
  25.  
  26.     render(data); 
  27.   }); 

「好的寫(xiě)法」

 
 
 
  1. function showEmployeeList(employees) { 
  2.   employees.forEach(employee => { 
  3.     const expectedSalary = employee.calculateExpectedSalary(); 
  4.     const experience = employee.getExperience(); 
  5.  
  6.     const data = { 
  7.       expectedSalary, 
  8.       experience 
  9.     }; 
  10.  
  11.     switch (employee.type) { 
  12.       case "manager": 
  13.         data.portfolio = employee.getMBAProjects(); 
  14.         break; 
  15.       case "developer": 
  16.         data.githubLink = employee.getGithubLink(); 
  17.         break; 
  18.     } 
  19.  
  20.     render(data); 
  21.   }); 

使用Object.assign設(shè)置默認(rèn)對(duì)象

「不好的寫(xiě)法」

 
 
 
  1. const menuConfig = { 
  2.   title: null, 
  3.   body: "Bar", 
  4.   buttonText: null, 
  5.   cancellable: true 
  6. }; 
  7.  
  8. function createMenu(config) { 
  9.   configconfig.title = config.title || "Foo"; 
  10.   configconfig.body = config.body || "Bar"; 
  11.   configconfig.buttonText = config.buttonText || "Baz"; 
  12.   configconfig.cancellable = 
  13.     config.cancellable !== undefined ? config.cancellable : true; 
  14.  
  15. createMenu(menuConfig); 

「好的寫(xiě)法」

 
 
 
  1. const menuConfig = { 
  2.   title: "Order", 
  3.   // User did not include 'body' key 
  4.   buttonText: "Send", 
  5.   cancellable: true 
  6. }; 
  7.  
  8. function createMenu(config) { 
  9.   config = Object.assign( 
  10.     { 
  11.       title: "Foo", 
  12.       body: "Bar", 
  13.       buttonText: "Baz", 
  14.       cancellable: true 
  15.     }, 
  16.     config 
  17.   ); 
  18.  
  19.   // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} 
  20.   // ... 
  21.  
  22. createMenu(menuConfig); 

不要使用標(biāo)志作為函數(shù)參數(shù)

標(biāo)志告訴使用者,此函數(shù)可以完成多項(xiàng)任務(wù),函數(shù)應(yīng)該做一件事。如果函數(shù)遵循基于布爾的不同代碼路徑,請(qǐng)拆分它們。

 
 
 
  1. // 不好的寫(xiě)法 
  2. function createFile(name, temp) { 
  3.   if (temp) { 
  4.     fs.create(`./temp/${name}`); 
  5.   } else { 
  6.     fs.create(name); 
  7.   } 
  8.  
  9. // 好的寫(xiě)法 
  10. function createFile(name) { 
  11.   fs.create(name); 
  12.  
  13. function createTempFile(name) { 
  14.   createFile(`./temp/${name}`); 

避免副作用(第一部分)

如果函數(shù)除了接受一個(gè)值并返回另一個(gè)值或多個(gè)值以外,不執(zhí)行任何其他操作,都會(huì)產(chǎn)生副作用。副作用可能是寫(xiě)入文件,修改某些全局變量,或者不小心將你的所有資金都匯給了陌生人。

「不好的寫(xiě)法」

 
 
 
  1. let name = "Ryan McDermott"; 
  2.  
  3. function splitIntoFirstAndLastName() { 
  4.   namename = name.split(" "); 
  5.  
  6. splitIntoFirstAndLastName(); 
  7.  
  8. console.log(name); // ['Ryan', 'McDermott']; 

「好的寫(xiě)法」

 
 
 
  1. function splitIntoFirstAndLastName(name) { 
  2.   return name.split(" "); 
  3.  
  4. const name = "Ryan McDermott"; 
  5. const newName = splitIntoFirstAndLastName(name); 
  6.  
  7. console.log(name); // 'Ryan McDermott'; 
  8. console.log(newName); // ['Ryan', 'McDermott']; 

避免副作用(第二部分)

在JavaScript中,原始類(lèi)型值是按值傳遞,而對(duì)象/數(shù)組按引用傳遞。對(duì)于對(duì)象和數(shù)組,如果有函數(shù)在購(gòu)物車(chē)數(shù)組中進(jìn)行了更改(例如,通過(guò)添加要購(gòu)買(mǎi)的商品),則使用該購(gòu)物車(chē)數(shù)組的任何其他函數(shù)都將受到此添加的影響。那可能很棒,但是也可能不好。來(lái)想象一個(gè)糟糕的情況:

用戶單擊“購(gòu)買(mǎi)”按鈕,該按鈕調(diào)用一個(gè)purchase 函數(shù),接著,該函數(shù)發(fā)出一個(gè)網(wǎng)絡(luò)請(qǐng)求并將cart數(shù)組發(fā)送到服務(wù)器。由于網(wǎng)絡(luò)連接不好,purchase函數(shù)必須不斷重試請(qǐng)求。現(xiàn)在,如果在網(wǎng)絡(luò)請(qǐng)求開(kāi)始之前,用戶不小心點(diǎn)擊了他們實(shí)際上不需要的項(xiàng)目上的“添加到購(gòu)物車(chē)”按鈕,該怎么辦?如果發(fā)生這種情況,并且網(wǎng)絡(luò)請(qǐng)求開(kāi)始,那么購(gòu)買(mǎi)函數(shù)將發(fā)送意外添加的商品,因?yàn)樗幸粋€(gè)對(duì)購(gòu)物車(chē)數(shù)組的引用,addItemToCart函數(shù)通過(guò)添加修改了這個(gè)購(gòu)物車(chē)數(shù)組。

一個(gè)很好的解決方案是addItemToCart總是克隆cart數(shù)組,編輯它,然后返回克隆。這可以確保購(gòu)物車(chē)引用的其他函數(shù)不會(huì)受到任何更改的影響。

關(guān)于這種方法有兩點(diǎn)需要注意:

  • 可能在某些情況下,我們確實(shí)需要修改輸入對(duì)象,但是當(dāng)我們采用這種編程實(shí)踐時(shí),會(huì)發(fā)現(xiàn)這種情況非常少見(jiàn),大多數(shù)東西都可以被改造成沒(méi)有副作用。
  • 就性能而言,克隆大對(duì)象可能會(huì)非常昂貴。幸運(yùn)的是,在實(shí)踐中這并不是一個(gè)大問(wèn)題,因?yàn)橛泻芏嗪馨舻膸?kù)使這種編程方法能夠快速進(jìn)行,并且不像手動(dòng)克隆對(duì)象和數(shù)組那樣占用大量?jī)?nèi)存。
 
 
 
  1. // 不好的寫(xiě)法 
  2. const addItemToCart = (cart, item) => { 
  3.   cart.push({ item, date: Date.now() }); 
  4. }; 
  5.  
  6. // 好的寫(xiě)法 
  7. const addItemToCart = (cart, item) => { 
  8.   return [...cart, { item, date: Date.now() }]; 
  9. }; 

不要寫(xiě)全局函數(shù)

污染全局變量在 JS 中是一種不好的做法,因?yàn)榭赡軙?huì)與另一個(gè)庫(kù)發(fā)生沖突,并且在他們的生產(chǎn)中遇到異常之前,API 的用戶將毫無(wú)用處。讓我們考慮一個(gè)示例:如果想擴(kuò)展 JS 的原生Array方法以具有可以顯示兩個(gè)數(shù)組之間差異的diff方法,該怎么辦?可以將新函數(shù)寫(xiě)入Array.prototype,但它可能與另一個(gè)嘗試執(zhí)行相同操作的庫(kù)發(fā)生沖突。如果其他庫(kù)僅使用diff來(lái)查找數(shù)組的第一個(gè)元素和最后一個(gè)元素之間的區(qū)別怎么辦?這就是為什么只使用 ES6 類(lèi)并簡(jiǎn)單地?cái)U(kuò)展Array全局會(huì)更好的原因。

 
 
 
  1. // 不好的寫(xiě)法 
  2. Array.prototype.diff = function diff(comparisonArray) { 
  3.   const hash = new Set(comparisonArray); 
  4.   return this.filter(elem => !hash.has(elem)); 
  5. }; 
  6.  
  7. // 好的寫(xiě)法 
  8. class SuperArray extends Array { 
  9.   diff(comparisonArray) { 
  10.     const hash = new Set(comparisonArray); 
  11.     return this.filter(elem => !hash.has(elem)); 
  12.   } 

盡量使用函數(shù)式編程而非命令式

JavaScript不像Haskell那樣是一種函數(shù)式語(yǔ)言,但它具有函數(shù)式的風(fēng)格。函數(shù)式語(yǔ)言可以更簡(jiǎn)潔、更容易測(cè)試。如果可以的話,盡量喜歡這種編程風(fēng)格。

「不好的寫(xiě)法」

 
 
 
  1. const programmerOutput = [ 
  2.   { 
  3.     name: "Uncle Bobby", 
  4.     linesOfCode: 500 
  5.   }, 
  6.   { 
  7.     name: "Suzie Q", 
  8.     linesOfCode: 1500 
  9.   }, 
  10.   { 
  11.     name: "Jimmy Gosling", 
  12.     linesOfCode: 150 
  13.   }, 
  14.   { 
  15.     name: "Gracie Hopper", 
  16.     linesOfCode: 1000 
  17.   } 
  18. ]; 
  19.  
  20. let totalOutput = 0; 
  21.  
  22. for (let i = 0; i < programmerOutput.length; i++) { 
  23.   totalOutput += programmerOutput[i].linesOfCode; 

「好的寫(xiě)法」

 
 
 
  1. const programmerOutput = [ 
  2.   { 
  3.     name: "Uncle Bobby", 
  4.     linesOfCode: 500 
  5.   }, 
  6.   { 
  7.     name: "Suzie Q", 
  8.     linesOfCode: 1500 
  9.   }, 
  10.   { 
  11.     name: "Jimmy Gosling", 
  12.     linesOfCode: 150 
  13.   }, 
  14.   { 
  15.     name: "Gracie Hopper", 
  16.     linesOfCode: 1000 
  17.   } 
  18. ]; 
  19.  
  20. const totalOutput = programmerOutput.reduce( 
  21.   (totalLines, output) => totalLines + output.linesOfCode, 
  22.   0 
  23. ); 

封裝條件

 
 
 
  1. // 不好的寫(xiě)法 
  2. if (fsm.state === "fetching" && isEmpty(listNode)) { 
  3.   // ... 
  4.  
  5. // 好的寫(xiě)法 
  6. function shouldShowSpinner(fsm, listNode) { 
  7.   return fsm.state === "fetching" && isEmpty(listNode); 
  8.  
  9. if (shouldShowSpinner(fsmInstance, listNodeInstance)) { 
  10.   // ... 

避免使用非條件

 
 
 
  1. // 不好的寫(xiě)法 
  2. function isDOMNodeNotPresent(node) { 
  3.   // ... 
  4.  
  5. if (!isDOMNodeNotPresent(node)) { 
  6.   // ... 
  7.  
  8. // 好的寫(xiě)法 
  9. function isDOMNodePresent(node) { 
  10.   // ... 
  11.  
  12. if (isDOMNodePresent(node)) { 
  13.   // ... 

避免使用過(guò)多條件

這似乎是一個(gè)不可能完成的任務(wù)。一聽(tīng)到這個(gè),大多數(shù)人會(huì)說(shuō),“沒(méi)有if語(yǔ)句,我怎么能做任何事情呢?”答案是,你可以在許多情況下使用多態(tài)性來(lái)實(shí)現(xiàn)相同的任務(wù)。

第二個(gè)問(wèn)題通常是,“那很好,但是我為什么要那樣做呢?”答案是上面講過(guò)一個(gè)概念:一個(gè)函數(shù)應(yīng)該只做一件事。當(dāng)具有if語(yǔ)句的類(lèi)和函數(shù)時(shí),這是在告訴你的使用者該函數(shù)執(zhí)行不止一件事情。

「不好的寫(xiě)法」

 
 
 
  1. class Airplane { 
  2.   // ... 
  3.   getCruisingAltitude() { 
  4.     switch (this.type) { 
  5.       case "777": 
  6.         return this.getMaxAltitude() - this.getPassengerCount(); 
  7.       case "Air Force One": 
  8.         return this.getMaxAltitude(); 
  9.       case "Cessna": 
  10.         return this.getMaxAltitude() - this.getFuelExpenditure(); 
  11.     } 
  12.   } 

「好的寫(xiě)法」

 
 
 
  1. class Airplane { 
  2.   // ... 
  3.  
  4. class Boeing777 extends Airplane { 
  5.   // ... 
  6.   getCruisingAltitude() { 
  7.     return this.getMaxAltitude() - this.getPassengerCount(); 
  8.   } 
  9.  
  10. class AirForceOne extends Airplane { 
  11.   // ... 
  12.   getCruisingAltitude() { 
  13.     return this.getMaxAltitude(); 
  14.   } 
  15.  
  16. class Cessna extends Airplane { 
  17.   // ... 
  18.   getCruisingAltitude() { 
  19.     return this.getMaxAltitude() - this.getFuelExpenditure(); 
  20.   } 

避免類(lèi)型檢查

JavaScript 是無(wú)類(lèi)型的,這意味著函數(shù)可以接受任何類(lèi)型的參數(shù)。有時(shí)q我們會(huì)被這種自由所困擾,并且很想在函數(shù)中進(jìn)行類(lèi)型檢查。有很多方法可以避免這樣做。首先要考慮的是一致的API。

 
 
 
  1. // 不好的寫(xiě)法 
  2. function travelToTexas(vehicle) { 
  3.   if (vehicle instanceof Bicycle) { 
  4.     vehicle.pedal(this.currentLocation, new Location("texas")); 
  5.   } else if (vehicle instanceof Car) { 
  6.     vehicle.drive(this.currentLocation, new Location("texas")); 
  7.   } 
  8.  
  9. // 好的寫(xiě)法 
  10. function travelToTexas(vehicle) { 
  11.   vehicle.move(this.currentLocation, new Location("texas")); 

不要過(guò)度優(yōu)化

現(xiàn)代瀏覽器在運(yùn)行時(shí)做了大量的優(yōu)化工作。很多時(shí)候,如果你在優(yōu)化,那么你只是在浪費(fèi)時(shí)間。有很好的資源可以查看哪里缺乏優(yōu)化,我們只需要針對(duì)需要優(yōu)化的地方就行了。

 
 
 
  1. // 不好的寫(xiě)法 
  2.  
  3. // 在舊的瀏覽器上,每一次使用無(wú)緩存“l(fā)ist.length”的迭代都是很昂貴的 
  4. // 會(huì)為“l(fā)ist.length”重新計(jì)算。在現(xiàn)代瀏覽器中,這是經(jīng)過(guò)優(yōu)化的 
  5. for (let i = 0, len = list.length; i < len; i++) { 
  6.   // ... 
  7.  
  8. // 好的寫(xiě)法 
  9. for (let i = 0; i < list.length; i++) { 
  10.   // ... 

網(wǎng)頁(yè)標(biāo)題:如何寫(xiě)出優(yōu)雅的JS代碼,變量和函數(shù)的正確寫(xiě)法
本文地址:http://www.5511xx.com/article/dhigphg.html