加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

如何写出优雅耐看的JavaScript代码

发布时间:2019-09-20 21:37:36 所属栏目:优化 来源:浅夏晴空
导读:副标题#e# 前言 在我们平时的工作开发中,大多数都是大人协同开发的公共项目;在我们平时开发中代码codeing的时候我们考虑代码的可读性、复用性和扩展性。 干净的代码,既在质量上较为可靠,也为后期维护、升级奠定了良好基

这样写用到了es6里的Map对象,是不是更爽了?Map对象和Object对象有什么区别呢?

  • 一个对象通常都有自己的原型,所以一个对象总有一个"prototype"键。
  • 一个对象的键只能是字符串或者Symbols,但一个Map的键可以是任意值。

你可以通过size属性很容易地得到一个Map的键值对个数,而对象的键值对个数只能手动确认。

代码风格

常量大写

  1. //bad code 
  2. const DAYS_IN_WEEK = 7; 
  3. const daysInMonth = 30; 
  4.  
  5. const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; 
  6. const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles']; 
  7.  
  8. function eraseDatabase() {} 
  9. function restore_database() {} 
  10.  
  11. class animal {} 
  12. class Alpaca {} 
  13.  
  14. //better code 
  15. const DAYS_IN_WEEK = 7; 
  16. const DAYS_IN_MONTH = 30; 
  17.  
  18. const SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']; 
  19. const ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles']; 
  20.  
  21. function eraseDatabase() {} 
  22. function restoreDatabase() {} 
  23.  
  24. class Animal {} 
  25. class Alpaca {} 

先声明后调用

  1. //bad code 
  2. class PerformanceReview { 
  3.   constructor(employee) { 
  4.     this.employee = employee; 
  5.   } 
  6.  
  7.   lookupPeers() { 
  8.     return db.lookup(this.employee, 'peers'); 
  9.   } 
  10.  
  11.   lookupManager() { 
  12.     return db.lookup(this.employee, 'manager'); 
  13.   } 
  14.  
  15.   getPeerReviews() { 
  16.     const peers = this.lookupPeers(); 
  17.     // ... 
  18.   } 
  19.  
  20.   perfReview() { 
  21.     this.getPeerReviews(); 
  22.     this.getManagerReview(); 
  23.     this.getSelfReview(); 
  24.   } 
  25.  
  26.   getManagerReview() { 
  27.     const manager = this.lookupManager(); 
  28.   } 
  29.  
  30.   getSelfReview() { 
  31.     // ... 
  32.   } 
  33.  
  34. const review = new PerformanceReview(employee); 
  35. review.perfReview(); 
  36.  
  37. //better code 
  38. class PerformanceReview { 
  39.   constructor(employee) { 
  40.     this.employee = employee; 
  41.   } 
  42.  
  43.   perfReview() { 
  44.     this.getPeerReviews(); 
  45.     this.getManagerReview(); 
  46.     this.getSelfReview(); 
  47.   } 
  48.  
  49.   getPeerReviews() { 
  50.     const peers = this.lookupPeers(); 
  51.     // ... 
  52.   } 
  53.  
  54.   lookupPeers() { 
  55.     return db.lookup(this.employee, 'peers'); 
  56.   } 
  57.  
  58.   getManagerReview() { 
  59.     const manager = this.lookupManager(); 
  60.   } 
  61.  
  62.   lookupManager() { 
  63.     return db.lookup(this.employee, 'manager'); 
  64.   } 
  65.  
  66.   getSelfReview() { 
  67.     // ... 
  68.   } 
  69.  
  70. const review = new PerformanceReview(employee); 
  71. review.perfReview(); 

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读