ITPub博客

首页 > IT职业 > IT图书 > JavaScript 代码整洁之道(上)

JavaScript 代码整洁之道(上)

IT图书 作者:sbzyg 时间:2021-09-09 09:06:06 0 删除 编辑
介绍
  • 变量
  • 函数
  • 对象和数据结构
  • 原作者根据《代码整洁之道》总结的适用于 JavaScript 软件工程的原则。

    本文是对作者英文原文《Clean Code JavaScript》的翻译整理。

    真正需要优化的地方

    Bad:

    
    // 这里使用变量len是因为在老式浏览器中,
    // 直接使用正例中的方式会导致每次循环均重复计算list.length的值,
    // 而在现代浏览器中会自动完成优化,这一行为是没有必要的
    for (var i = 0, len = list.length; i 

    Good:

    for (var i = 0; i 

    删除无效的代码

    不再被调用的代码应及时删除。

    Bad:

    function oldRequestModule(url) {
      // ...
    }
    
    function newRequestModule(url) {
      // ...
    }
    
    var req = newRequestModule;
    inventoryTracker('apples', req, 'www.inventory-awesome.io');
    

    Good:

    function newRequestModule(url) {
      // ...
    }
    
    var req = newRequestModule;
    inventoryTracker('apples', req, 'www.inventory-awesome.io');
    对象和数据结构

    使用 getters 和 setters

    JS 没有接口或类型,因此实现这一模式是很困难的,因为我们并没有类似 public 和 private 的关键词。

    而使用 getters 和 setters 获取对象的数据,远比直接使用“点”操作符具有优势,原因:

    1. 当需要对获取的对象属性执行额外操作时,执行 set 时可以增加规则对要变量的合法性进行判断
    2. 封装了内部逻辑,在存取时可以方便的增加日志和错误处理
    3. 继承该类时可以重载默认行为
    4. 从服务器获取数据时可以进行懒加载

    Bad:

    class BankAccount {
      constructor() {
        this.balance = 1000;
      }
    }
    
    let bankAccount = new BankAccount();
    
    // Buy shoes...
    bankAccount.balance = bankAccount.balance - 100;

    Good:

    class BankAccount {
      constructor() {
        this.balance = 1000;
      }
    
      // It doesn't have to be prefixed with `get` or `set` to be a getter/setter
      withdraw(amount) {
        if (verifyAmountCanBeDeducted(amount)) {
          this.balance -= amount;
        }
      }
    }
    
    let bankAccount = new BankAccount();
    
    // Buy shoes...
    bankAccount.withdraw(100);

    让对象拥有私有成员

    可以通过闭包完成

    Bad:

    
    var Employee = function(name) {
      this.name = name;
    }
    
    Employee.prototype.getName = function() {
      return this.name;
    }
    
    var employee = new Employee('John Doe');
    console.log('Employee name: ' + employee.getName()); // Employee name: John Doe
    delete employee.name;
    console.log('Employee name: ' + employee.getName()); // Employee name: undefined

    Good:

    var Employee = (function() {
      function Employee(name) {
        this.getName = function() {
          return name;
        };
      }
    
      return Employee;
    }());
    
    var employee = new Employee('John Doe');
    console.log('Employee name: ' + employee.getName()); // Employee name: John Doe
    delete employee.name;
    console.log('Employee name: ' + employee.getName()); // Employee name: John Doe

    来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2353/viewspace-2799421/ ,如需转载,请注明出处,否则将追究法律责任。

    请登录后发表评论 登录
    全部评论

    注册时间:2019-08-15

    • 博文量
      101
    • 访问量
      624