美文网首页
写出漂亮的 JavaScript 代码

写出漂亮的 JavaScript 代码

作者: Fight_Code | 来源:发表于2019-07-05 16:51 被阅读0次

函数

如果参数超过两个,建议使用 ES6 的解构语法,不用考虑参数的顺序。
function createMenu( { title, body, buttonText, cancellable } ) {
    // ...
}
尽量不要写全局方法

使用 ES6 的 class

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

// Good:
// 动物
class Animal {
  constructor(age) {
    this.age = age
  };
  move() {};
}
// 哺乳动物
class Mammal extends Animal{
  constructor(age, furColor) {
    super(age);
    this.furColor = furColor;
  };
  liveBirth() {};
}
// 人类
class Human extends Mammal{
  constructor(age, furColor, languageSpoken) {
    super(age, furColor);
    this.languageSpoken = languageSpoken;
  };
  speak() {};
}

使用链式调用
class Car {
  constructor(make, model, color) {
    this.make = make;
    this.model = model;
    this.color = color;
  }

  setMake(make) {
    this.make = make;
  }

  setModel(model) {
    this.model = model;
  }

  setColor(color) {
    this.color = color;
  }

  save() {
    console.log(this.make, this.model, this.color);
  }
}
// Bad:
const car = new Car('Ford','F-150','red');
car.setColor('pink');
car.save();

// Good: 
class Car {
  constructor(make, model, color) {
    this.make = make;
    this.model = model;
    this.color = color;
  }

  setMake(make) {
    this.make = make;
    // NOTE: Returning this for chaining
    return this;
  }

  setModel(model) {
    this.model = model;
    // NOTE: Returning this for chaining
    return this;
  }

  setColor(color) {
    this.color = color;
    // NOTE: Returning this for chaining
    return this;
  }

  save() {
    console.log(this.make, this.model, this.color);
    // NOTE: Returning this for chaining
    return this;
  }
}

const car = new Car("Ford", "F-150", "red").setColor("pink").save();

相关文章

  • 写出漂亮的 JavaScript 代码

    函数 如果参数超过两个,建议使用 ES6 的解构语法,不用考虑参数的顺序。 尽量不要写全局方法 类 使用 ES6 ...

  • 如何写出漂亮的 JavaScript 代码

    为了帮助大家提高代码的可读性、复用性、扩展性。我们将从以下四个方面讨论如何写好js代码: 变量、函数、类、异步 一...

  • 写出漂亮的代码

    最近在知乎新开了一个专栏,写出漂亮的代码 写一个功能 能上生产 可能只需要两天 要让代码符有一定的美感 则需要反复...

  • Javascript代码规范

    目的:总结记录Javascript代码书写规范,写出优美的Javascript代码,代码洁癖只是一种态度。 一、命...

  • 写出整洁的 JavaScript 代码

    前言 每个人写代码风格不一样,但本文给出了十个不同正反例说明,大家可以多参考,但不一定要遵守。本文由@aliveb...

  • 不仅要写出漂亮的代码,也要写出漂亮的注释

    几乎所有的软件工程师,都追求写出漂亮的代码,但是在学如何写好代码的同时,却很少有人关注写好代码注释的重要性,有的工...

  • 写出更优秀的javascript代码

    类型 在使用复合类型时需要注意其引用: 变量声明与赋值 使用let, const 代替 var: let 和 co...

  • 使用 ESLint、Prettier 和 Husky 建立高效的

    Linting 和漂亮打印的 JavaScript 代码有助于更早地检测错误,使代码更清晰,并提高整体代码质量。但...

  • Clean Code之JavaScript代码示例

    译者按: 简洁的代码可以避免写出过多的BUG。 原文: JavaScript Clean Code - Best ...

  • 前端之路

    把握代码质量,写出优雅,可读性高,易维护,符合开放-封闭原则的代码了解掌握javascript常用的设计模式,并能...

网友评论

      本文标题:写出漂亮的 JavaScript 代码

      本文链接:https://www.haomeiwen.com/subject/muiehctx.html