对象与数据结构
使用Getter和Setter方法
通过Getter和Setter方法访问对象数据相比直接访问属性更具优势。你可能会问:"为什么?" 以下是一个未详细分类的理由列表:
- 当需要在获取对象属性之外进行更多操作时,无需查找并修改代码中的每个访问点
- 执行
set操作时可轻松实现数据验证 - 封装内部表示形式
- 便于在属性存取时添加日志记录与错误处理
- 支持属性延迟加载,例如从服务器按需加载数据
反例:
javascript
function makeBankAccount() {
// ...
return {
balance: 0
// ...
};
}
const account = makeBankAccount();
account.balance = 100;正例:
javascript
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);使对象具有私有成员
可通过闭包机制实现(适用于ES5及以下版本)
反例:
javascript
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正例:
javascript
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