• 前端代码规范


    前端代码规范

    变量

    1、使用有意义且易懂的变量名

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

    2、对相同类型的变量使用相同的根词汇

    Bad:
    getUserInfo(); getClientData(); getCustomerRecord();
    Good:
    getUserInfo(); getUserData(); getUserRecord();
    
    • 1
    • 2
    • 3
    • 4

    3、编写的代码是可读和可搜索的

    Bad:
    // What the heck is 86400000 for? 
    setTimeout(blastOff, 86400000);
    Good:
    // Declare them as capitalized named constants. 
    const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000; 
    setTimeout(blastOff, MILLISECONDS_PER_DAY);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4、使用解释变量

    Bad:

    const address = "One Infinite Loop, Cupertino 95014"; 
    const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 
    saveCityZipCode(   address.match(cityZipCodeRegex)[1],   address.match(cityZipCodeRegex)[2] );
    
    • 1
    • 2
    • 3

    Good:

    const address = "One Infinite Loop, Cupertino 95014"; 
    const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 
    const [_, city, zipCode] = address.match(cityZipCodeRegex) || []; saveCityZipCode(city, zipCode);
    
    • 1
    • 2
    • 3

    5、显式优于隐式

    Bad:

    const locations = ["Austin", "New York", "San Francisco"]; 
    locations.forEach(l => {   
    doStuff();   
    doSomeOtherStuff(); 
       // Wait, what is `l` for again? 
      dispatch(l); });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Good:

    const locations = ["Austin", "New York", "San Francisco"]; 
    locations.forEach(location => { 
      doStuff(); 
      doSomeOtherStuff(); 
     dispatch(location); 
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    6、如果你的类/对象名告诉了你什么,不要在变量名中重复。

    Bad:

    const Car = {   carMake: "Honda",   carModel: "Accord",   carColor: "Blue" }; 
    function paintCar(car, color) {   
    car.carColor = color; 
    }
    
    • 1
    • 2
    • 3
    • 4

    Good:

    const Car = {   make: "Honda",   model: "Accord",   color: "Blue" }; 
    function paintCar(car, color) {   
    car.color = color; 
    }
    
    • 1
    • 2
    • 3
    • 4

    7、默认参数是更干净的写法

    Bad:

    function createMicrobrewery(name) 
    {   const breweryName = name || "Hipster Brew Co.";  
     // ... }
    
    • 1
    • 2
    • 3

    Good:

    function createMicrobrewery(name = "Hipster Brew Co.") 
    {   // ... }
    
    • 1
    • 2

    方法

    1、参数数量小于等于2

    Bad:

    function createMenu(title, body, buttonText, cancellable) {
      // ...
    }
    createMenu("Foo", "Bar", "Baz", true);
    
    • 1
    • 2
    • 3
    • 4

    Good:

    function createMenu({ title, body, buttonText, cancellable }) {
      // ...
    }
    createMenu({
      title: "Foo",
      body: "Bar",
      buttonText: "Baz",
      cancellable: true
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2、单一功能性

    Bad:

    function emailClients(clients) {
      clients.forEach(client => {
        const clientRecord = database.lookup(client);
        if (clientRecord.isActive()) {
          email(client);
        }
      });
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Good:

    function emailActiveClients(clients) {
      clients.filter(isActiveClient).forEach(email);
    }
    function isActiveClient(client) {
      const clientRecord = database.lookup(client);
      return clientRecord.isActive();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3、函数名告诉我们他是做什么的

    Bad:

    function addToDate(date, month) {
      // ...
    }
    
    
    const date = new Date();
    // It's hard to tell from the function name what is added
    addToDate(date, 1);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Good:

    function addMonthToDate(month, date) {
      // ...
    }
    const date = new Date();
    addMonthToDate(1, date);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4、删除重复代码

    Bad:

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

    Good:

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

    5、使用Object.assign设置默认对象

    Bad:

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

    Good:

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

    6、不要将标志用作函数参数

    Bad:

    function createFile(name, temp) {
      if (temp) {
        fs.create(`./temp/${name}`);
      } else {
        fs.create(name);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Good:

    function createFile(name) {
      fs.create(name);
    }
    function createTempFile(name) {
      createFile(`./temp/${name}`);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    7、避免副作用函数

    Bad:

    // Global variable referenced by following function.
    // If we had another function that used this name, now it'd be an array and it could break it.
    let name = "Ryan McDermott";
    function splitIntoFirstAndLastName() {
      name = name.split(" ");
    }
    splitIntoFirstAndLastName();
    console.log(name); // ['Ryan', 'McDermott'];
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Good:

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

    8、条件封装为函数

    Bad:

    if (fsm.state === "fetching" && isEmpty(listNode)) {
      // ...
    }
    
    • 1
    • 2
    • 3

    Good:

    function shouldShowSpinner(fsm, listNode) {
      return fsm.state === "fetching" && isEmpty(listNode);
    }
    if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
      // ...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    9、避免否定条件

    Bad:

    function isDOMNodeNotPresent(node) {
      // ...
    }
    if (!isDOMNodeNotPresent(node)) {
      // ...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Good:

    function isDOMNodePresent(node) {
      // ...
    }
    if (isDOMNodePresent(node)) {
      // ...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    10、移除 deadcode

    Bad:

    function oldRequestModule(url) {
      // ...
    }
    function newRequestModule(url) {
      // ...
    }
    const req = newRequestModule;
    inventoryTracker("apples", req, "www.inventory-awesome.io");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Good:

    function newRequestModule(url) {
      // ...
    }
    const req = newRequestModule;
    inventoryTracker("apples", req, "www.inventory-awesome.io");
    
    • 1
    • 2
    • 3
    • 4
    • 5

    对象和数据结构

    1、用set get修改数据

    Bad:

    function makeBankAccount() {
      // ...
      return {
        balance: 0
        // ...
      };
    }
    const account = makeBankAccount();
    account.balance = 100;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    Good:

    function makeBankAccount() {
      // this one is private
      let balance = 0;
      // a "getter", made public via the returned object below
      function getBalance() {
        return balance;
      }
      // a "setter", made public via the returned object below
      function setBalance(amount) {
        // ... validate before updating the balance
        balance = amount;
      }
      return {
        // ...
        getBalance,
        setBalance
      };
    }
    const account = makeBankAccount();
    account.setBalance(100);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    Class

    1、方法使用链式调用

    Bad:

    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);
      }
    }
    const car = new Car("Ford", "F-150", "red");
    car.setColor("pink");
    car.save();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    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();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    异步请求

    Use Promises, not callbacks

    Bad:

    import { get } from "request";
    import { writeFile } from "fs";
    get(
      "https://en.wikipedia.org/wiki/Robert_Cecil_Martin",
      (requestErr, response, body) => {
        if (requestErr) {
          console.error(requestErr);
        } else {
          writeFile("article.html", body, writeErr => {
            if (writeErr) {
              console.error(writeErr);
            } else {
              console.log("File written");
            }
          });
        }
      }
    );
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    Good:

    import { get } from "request-promise";
    import { writeFile } from "fs-extra";
    get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
      .then(body => {
        return writeFile("article.html", body);
      })
      .then(() => {
        console.log("File written");
      })
      .catch(err => {
        console.error(err);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    Async/Await are even cleaner than Promises

    Bad:

    import { get } from "request-promise";
    import { writeFile } from "fs-extra";
    get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
      .then(body => {
        return writeFile("article.html", body);
      })
      .then(() => {
        console.log("File written");
      })
      .catch(err => {
        console.error(err);
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    Good:

    import { get } from "request-promise";
    import { writeFile } from "fs-extra";
    async function getCleanCodeArticle() {
      try {
        const body = await get(
          "https://en.wikipedia.org/wiki/Robert_Cecil_Martin"
        );
        await writeFile("article.html", body);
        console.log("File written");
      } catch (err) {
        console.error(err);
      }
    }
    getCleanCodeArticle()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3、错误捕获

    Bad:

    try {
      functionThatMightThrow();
    } catch (error) {
      console.log(error);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Good:

    try {
      functionThatMightThrow();
    } catch (error) {
      // One option (more noisy than console.log):
      console.error(error);
      // Another option:
      notifyUserOfError(error);
      // Another option:
      reportErrorToService(error);
      // OR do all three!
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    【正点原子I.MX6U-MINI应用篇】1、编写第一个应用App程序helloworld
    卷积神经网络-池化层和激活层
    axios是如何实现的(源码解析)
    代码随想录Day18 LeetCode235 二叉搜索树的公共祖先 T701二叉搜索树中的插入操作 T140 删除二叉搜索树中的公共节点
    仿英雄联盟网页HTML代码 学生网页设计与制作期末作业下载 大学生网页设计与制作成品下载 DW游戏介绍网页作业代码下载
    vue项目中实际封装DateRangePicker组件使用
    springboot晋韵戏剧点播网站设计毕业设计源码112304
    PHP遇见错误了看不懂?这些错误提示你必须搞懂
    Python list列表修改元素
    基于Ant Design设计语言的WinForm UI界面库
  • 原文地址:https://blog.csdn.net/weixin_44064067/article/details/127843722