- 对象和数据结构
- 使用 getters 和 setters
- 让对象拥有私有成员
对象和数据结构
使用 getters 和 setters
JS 没有接口或类型,因此实现这一模式是很困难的,因为我们并没有类似 public 和 private 的关键词。
然而,使用 getters 和 setters 获取对象的数据远比直接使用点操作符具有优势。为什么呢?
- 当需要对获取的对象属性执行额外操作时。
- 执行
set时可以增加规则对要变量的合法性进行判断。 - 封装了内部逻辑。
- 在存取时可以方便的增加日志和错误处理。
- 继承该类时可以重载默认行为。
- 从服务器获取数据时可以进行懒加载。
反例:
class BankAccount {constructor() {this.balance = 1000;}}let bankAccount = new BankAccount();// Buy shoes...bankAccount.balance = bankAccount.balance - 100;
正例:
class BankAccount {constructor() {this.balance = 1000;}// It doesn't have to be prefixed with `get` or `set` to be a getter/setterwithdraw(amount) {if (verifyAmountCanBeDeducted(amount)) {this.balance -= amount;}}}let bankAccount = new BankAccount();// Buy shoes...bankAccount.withdraw(100);
让对象拥有私有成员
可以通过闭包完成
反例:
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 Doedelete employee.name;console.log('Employee name: ' + employee.getName()); // Employee name: undefined
正例:
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 Doedelete employee.name;console.log('Employee name: ' + employee.getName()); // Employee name: John Doe
