美文网首页
写出漂亮的 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 代码

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