资讯专栏INFORMATION COLUMN

[译] 如何写出漂亮的 JavaScript 代码

amuqiao / 607人阅读

摘要:如何提高代码的可读性复用性扩展性。严格遵守这条规则会让你的代码可读性更好,也更容易重构。如果违反这个规则,那么代码会很难被测试或者重用。它让你的代码简洁优雅。

</>复制代码

  1. 原文:https://github.com/ryanmcderm...
    说明:本文翻译自 github 上的一个项目,非全文搬运,只取部分精华。

如何提高代码的可读性、复用性、扩展性。我们将从以下四个方面讨论:

变量

函数

异步

一、变量 用有意义且常用的单词命名

</>复制代码

  1. // Bad:
  2. const yyyymmdstr = moment().format("YYYY/MM/DD");
  3. // Good:
  4. const currentDate = moment().format("YYYY/MM/DD");
保持统一

对同一类型的变量使用相同的命名保持统一:

</>复制代码

  1. // Bad:
  2. getUserInfo();
  3. getClientData();
  4. getCustomerRecord();
  5. // Good:
  6. getUser()
每个常量(全大写)都该命名

可以用 ESLint 检测代码中未命名的常量。

</>复制代码

  1. // Bad:
  2. // 其他人知道 86400000 的意思吗?
  3. setTimeout( blastOff, 86400000 );
  4. // Good:
  5. const MILLISECOND_IN_A_DAY = 86400000;
  6. setTimeout( blastOff, MILLISECOND_IN_A_DAY );
避免无意义的命名

既然创建了一个 car 对象,就没有必要把它的颜色命名为 carColor。

</>复制代码

  1. // Bad:
  2. const car = {
  3. carMake: "Honda",
  4. carModel: "Accord",
  5. carColor: "Blue"
  6. };
  7. function paintCar( car ) {
  8. car.carColor = "Red";
  9. }
  10. // Good:
  11. const car = {
  12. make: "Honda",
  13. model: "Accord",
  14. color: "Blue"
  15. };
  16. function paintCar( car ) {
  17. car.color = "Red";
  18. }
传参使用默认值

</>复制代码

  1. // Bad:
  2. function createMicrobrewery( name ) {
  3. const breweryName = name || "Hipster Brew Co.";
  4. // ...
  5. }
  6. // Good:
  7. function createMicrobrewery( name = "Hipster Brew Co." ) {
  8. // ...
  9. }
二、函数 函数参数( 最好 2 个或更少 )

如果参数超过两个,建议使用 ES6 的解构语法,不用考虑参数的顺序。

</>复制代码

  1. // Bad:
  2. function createMenu( title, body, buttonText, cancellable ) {
  3. // ...
  4. }
  5. // Good:
  6. function createMenu( { title, body, buttonText, cancellable } ) {
  7. // ...
  8. }
  9. createMenu({
  10. title: "Foo",
  11. body: "Bar",
  12. buttonText: "Baz",
  13. cancellable: true
  14. });
一个方法只做一件事情

这是一条在软件工程领域流传久远的规则。严格遵守这条规则会让你的代码可读性更好,也更容易重构。如果违反这个规则,那么代码会很难被测试或者重用。

</>复制代码

  1. // Bad:
  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. // Good:
  11. function emailActiveClients( clients ) {
  12. clients
  13. .filter( isActiveClient )
  14. .forEach( email );
  15. }
  16. function isActiveClient( client ) {
  17. const clientRecord = database.lookup( client );
  18. return clientRecord.isActive();
  19. }
函数名上体现它的作用

</>复制代码

  1. // Bad:
  2. function addToDate( date, month ) {
  3. // ...
  4. }
  5. const date = new Date();
  6. // 很难知道是把什么加到日期中
  7. addToDate( date, 1 );
  8. // Good:
  9. function addMonthToDate( month, date ) {
  10. // ...
  11. }
  12. const date = new Date();
  13. addMonthToDate( 1, date );
删除重复代码,合并相似函数

很多时候虽然是同一个功能,但由于一两个不同点,让你不得不写两个几乎相同的函数。

</>复制代码

  1. // Bad:
  2. function showDeveloperList(developers) {
  3. developers.forEach((developer) => {
  4. const expectedSalary = developer.calculateExpectedSalary();
  5. const experience = developer.getExperience();
  6. const githubLink = developer.getGithubLink();
  7. const data = {
  8. expectedSalary,
  9. experience,
  10. githubLink
  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. render(data);
  26. });
  27. }
  28. // Good:
  29. function showEmployeeList(employees) {
  30. employees.forEach(employee => {
  31. const expectedSalary = employee.calculateExpectedSalary();
  32. const experience = employee.getExperience();
  33. const data = {
  34. expectedSalary,
  35. experience,
  36. };
  37. switch(employee.type) {
  38. case "develop":
  39. data.githubLink = employee.getGithubLink();
  40. break
  41. case "manager":
  42. data.portfolio = employee.getMBAProjects();
  43. break
  44. }
  45. render(data);
  46. })
  47. }
使用 Object.assign 设置默认属性

</>复制代码

  1. // Bad:
  2. const menuConfig = {
  3. title: null,
  4. body: "Bar",
  5. buttonText: null,
  6. cancellable: true
  7. };
  8. function createMenu(config) {
  9. config.title = config.title || "Foo";
  10. config.body = config.body || "Bar";
  11. config.buttonText = config.buttonText || "Baz";
  12. config.cancellable = config.cancellable !== undefined ? config.cancellable : true;
  13. }
  14. createMenu(menuConfig);
  15. // Good:
  16. const menuConfig = {
  17. title: "Order",
  18. // 不包含 body
  19. buttonText: "Send",
  20. cancellable: true
  21. };
  22. function createMenu(config) {
  23. config = Object.assign({
  24. title: "Foo",
  25. body: "Bar",
  26. buttonText: "Baz",
  27. cancellable: true
  28. }, config);
  29. // config : {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
  30. // ...
  31. }
  32. createMenu(menuConfig);
尽量不要写全局方法

在 JavaScript 中,永远不要污染全局,会在生产环境中产生难以预料的 bug。举个例子,比如你在 Array.prototype 上新增一个 diff 方法来判断两个数组的不同。而你同事也打算做类似的事情,不过他的 diff 方法是用来判断两个数组首位元素的不同。很明显你们方法会产生冲突,遇到这类问题我们可以用 ES2015/ES6 的语法来对 Array 进行扩展。

</>复制代码

  1. // Bad:
  2. Array.prototype.diff = function diff(comparisonArray) {
  3. const hash = new Set(comparisonArray);
  4. return this.filter(elem => !hash.has(elem));
  5. };
  6. // Good:
  7. class SuperArray extends Array {
  8. diff(comparisonArray) {
  9. const hash = new Set(comparisonArray);
  10. return this.filter(elem => !hash.has(elem));
  11. }
  12. }
尽量别用“非”条件句

</>复制代码

  1. // Bad:
  2. function isDOMNodeNotPresent(node) {
  3. // ...
  4. }
  5. if (!isDOMNodeNotPresent(node)) {
  6. // ...
  7. }
  8. // Good:
  9. function isDOMNodePresent(node) {
  10. // ...
  11. }
  12. if (isDOMNodePresent(node)) {
  13. // ...
  14. }
不要过度优化

现代浏览器已经在底层做了很多优化,过去的很多优化方案都是无效的,会浪费你的时间。

</>复制代码

  1. // Bad:
  2. // 现代浏览器已对此( 缓存 list.length )做了优化。
  3. for (let i = 0, len = list.length; i < len; i++) {
  4. // ...
  5. }
  6. // Good:
  7. for (let i = 0; i < list.length; i++) {
  8. // ...
  9. }
删除弃用代码

这里没有实例代码,删除就对了

三、类 使用 ES6 的 class

在 ES6 之前,没有类的语法,只能用构造函数的方式模拟类,可读性非常差。

</>复制代码

  1. // Good:
  2. // 动物
  3. class Animal {
  4. constructor(age) {
  5. this.age = age
  6. };
  7. move() {};
  8. }
  9. // 哺乳动物
  10. class Mammal extends Animal{
  11. constructor(age, furColor) {
  12. super(age);
  13. this.furColor = furColor;
  14. };
  15. liveBirth() {};
  16. }
  17. // 人类
  18. class Human extends Mammal{
  19. constructor(age, furColor, languageSpoken) {
  20. super(age, furColor);
  21. this.languageSpoken = languageSpoken;
  22. };
  23. speak() {};
  24. }
使用链式调用

这种模式相当有用,可以在很多库中都有使用。它让你的代码简洁优雅。

</>复制代码

  1. class Car {
  2. constructor(make, model, color) {
  3. this.make = make;
  4. this.model = model;
  5. this.color = color;
  6. }
  7. setMake(make) {
  8. this.make = make;
  9. }
  10. setModel(model) {
  11. this.model = model;
  12. }
  13. setColor(color) {
  14. this.color = color;
  15. }
  16. save() {
  17. console.log(this.make, this.model, this.color);
  18. }
  19. }
  20. // Bad:
  21. const car = new Car("Ford","F-150","red");
  22. car.setColor("pink");
  23. car.save();
  24. // Good:
  25. class Car {
  26. constructor(make, model, color) {
  27. this.make = make;
  28. this.model = model;
  29. this.color = color;
  30. }
  31. setMake(make) {
  32. this.make = make;
  33. // NOTE: Returning this for chaining
  34. return this;
  35. }
  36. setModel(model) {
  37. this.model = model;
  38. // NOTE: Returning this for chaining
  39. return this;
  40. }
  41. setColor(color) {
  42. this.color = color;
  43. // NOTE: Returning this for chaining
  44. return this;
  45. }
  46. save() {
  47. console.log(this.make, this.model, this.color);
  48. // NOTE: Returning this for chaining
  49. return this;
  50. }
  51. }
  52. const car = new Car("Ford", "F-150", "red").setColor("pink").save();
四、异步 使用 promise 或者 Async/Await 代替回调

</>复制代码

  1. // Bad:
  2. get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin", (requestErr, response) => {
  3. if (requestErr) {
  4. console.error(requestErr);
  5. } else {
  6. writeFile("article.html", response.body, (writeErr) => {
  7. if (writeErr) {
  8. console.error(writeErr);
  9. } else {
  10. console.log("File written");
  11. }
  12. });
  13. }
  14. });
  15. // Good:
  16. get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
  17. .then((response) => {
  18. return writeFile("article.html", response);
  19. })
  20. .then(() => {
  21. console.log("File written");
  22. })
  23. .catch((err) => {
  24. console.error(err);
  25. });
  26. // perfect:
  27. async function getCleanCodeArticle() {
  28. try {
  29. const response = await get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin");
  30. await writeFile("article.html", response);
  31. console.log("File written");
  32. } catch(err) {
  33. console.error(err);
  34. }
  35. }
后记

如果你想进【大前端交流群】,关注公众号点击“交流加群”添加机器人自动拉你入群。关注我第一时间接收最新干货。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/105035.html

相关文章

  • Top 15 - Material Design框架和类库()

    摘要:这是一个用于构建响应式应用和网站的前端框架。是基于设计的一套丰富的组件。这是一个对混合式手机应用框架的扩展库。到目前为止它仅大小,而且不依赖于任何第三方的插件,它可以很轻量的被用来创建和应用。 _Material design_是Google开发的,目的是为了统一公司的web端和手机端的产品风格。它是基于很多的原则,比如像合适的动画,响应式,以及颜色和阴影的使用。完整的指南详情请看这里...

    Cristic 评论0 收藏0
  • Top 15 - Material Design框架和类库()

    摘要:这是一个用于构建响应式应用和网站的前端框架。是基于设计的一套丰富的组件。这是一个对混合式手机应用框架的扩展库。到目前为止它仅大小,而且不依赖于任何第三方的插件,它可以很轻量的被用来创建和应用。 _Material design_是Google开发的,目的是为了统一公司的web端和手机端的产品风格。它是基于很多的原则,比如像合适的动画,响应式,以及颜色和阴影的使用。完整的指南详情请看这里...

    phpmatt 评论0 收藏0
  • []148个资源让你成为CSS专家

    摘要:层叠样式表二修订版这是对作出的官方说明。速查表两份表来自一份关于基础特性,一份关于布局。核心第一篇一份来自的基础参考指南简写速查表简写形式参考书使用层叠样式表基础指南,包含使用的好处介绍个方法快速写成高质量的写出高效的一些提示。 迄今为止,我已经收集了100多个精通CSS的资源,它们能让你更好地掌握CSS技巧,使你的布局设计脱颖而出。 CSS3 资源 20个学习CSS3的有用资源 C...

    impig33 评论0 收藏0
  • 2017-08-10 前端日报

    摘要:前端日报精选译用搭建探索生命周期中的匿名递归浏览器端机器智能框架深入理解笔记和属性中文上海线下活动前端工程化架构实践沪江技术沙龙掘金周二放送追加视频知乎专栏第期聊一聊前端自动化测试上双关语来自前端的小段子,你看得懂吗众成翻 2017-08-10 前端日报 精选 [译] 用 Node.js 搭建 API Gateway探索 Service Worker 「生命周期」JavaScript ...

    wupengyu 评论0 收藏0

发表评论

0条评论

amuqiao

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<