代碼整潔之道——3、對象和數據結構
阿新 • • 發佈:2017-07-25
ons amount 錯誤 setters 版本 整潔之道 fun john .proto
一、使用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
代碼整潔之道——3、對象和數據結構