• 代码整洁之道——3、对象和数据结构


    一、使用getters和setters

    使用getters和setters获取对象数据比简单查找对象属性要好。因为:

    1、当你想要做的不仅仅是获取对象属性,你不必查找和修改你代码中的每处访问。

    2、使用set可以使验证变简单。

    3、封装内部结构。

    4、使用get和set,容易打日志和处理错误。

    5、比如从服务器获取,你可以延迟加载你的对象属性(?)

    Bad:
    function makeBankAccount() {
      // ...
    
      return {
        balance: 0,
        // ...
      };
    }
    
    const account = makeBankAccount();
    account.balance = 100;
    
    Good:
    function makeBankAccount() {
      // 这是一个私有属性
      let balance = 0;
    
      // a "getter", 通过返回值使这个属性变成共有属性
      function getBalance() {
        return balance;
      }
    
      // a "setter", 通过返回值使这个属性变成共有属性
      function setBalance(amount) {
        // 在更新前验证
        balance = amount;
      }
    
      return {
        // ...
        getBalance,
        setBalance,
      };
    }
    
    const account = makeBankAccount();
    account.setBalance(100);

    二、让对象有私有成员

    这个可以通过闭包来实现(ES5及以下版本)

    Bad:
    const Employee = function(name) {
      this.name = name;
    };
    
    Employee.prototype.getName = function getName() {
      return this.name;
    };
    
    const 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:
    function makeEmployee(name) {
      return {
        getName() {
          return name;
        },
      };
    }
    
    const employee = makeEmployee('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
  • 相关阅读:
    spring
    23种设计模式
    get getline
    ping
    Android四大组件
    C++数据结构
    玩转windows便签
    [JavaScript]再谈 this
    [JavaScript]面向对象编程浅析之XJB讲
    [JavaScript]MVC浅析
  • 原文地址:https://www.cnblogs.com/xxchi/p/7236465.html
Copyright © 2020-2023  润新知