浅谈JavaScript 代码整洁之道(12)
使用方法链
在这里我的意见与《代码整洁之道》的观点不同。有人认为方法链不整洁,而且违反了得墨忒耳定律。也许他们是对的,但这个模式在 JavaScript 中非常有用,你可以很多库中看到,比如 jQuery 和 Lodash。它让代码变得既简洁又有表现力。在类中,只需要在每个函数结束前返回 this,就实现了链式调用的类方法。
不好:
class Car {
 constructor() {
  this.make = 'Honda';
  this.model = 'Accord';
  this.color = 'white';
 }
 setMake(make) {
  this.name = name;
 }
 setModel(model) {
  this.model = model;
 }
 setColor(color) {
  this.color = color;
 }
 save() {
  console.log(this.make, this.model, this.color);
 }
}
let car = new Car();
car.setColor('pink');
car.setMake('Ford');
car.setModel('F-150')
car.save();
好:
class Car {
 constructor() {
  this.make = 'Honda';
  this.model = 'Accord';
  this.color = 'white';
 }
 setMake(make) {
  this.name = name;
  // NOTE: 返回 this 以实现链式调用
  return this;
 }
 setModel(model) {
  this.model = model;
  // NOTE: 返回 this 以实现链式调用
  return this;
 }
 setColor(color) {
  this.color = color;
  // NOTE: 返回 this 以实现链式调用
  return this;
 }
 save() {
  console.log(this.make, this.model, this.color);
 }
}
let car = new Car()
 .setColor('pink')
 .setMake('Ford')
 .setModel('F-150')
 .save();
多用组合,少用继承
大家都知道 GoF 的设计模式,其中提到应该多用组合而不是继承。对于继承和组合,都有大量的理由在支撑,但这个准则的要点在于,你的想法本能地会想到继承,但这时候不防多思考一下用组合是否能更好的处理问题——某些时候,的确能。
你可能会考虑:“我什么时候该用继承?”这取决于你遇到的问题。这里有一个不错的清单说明了什么时候用继承比用组合更合适:
- 你的继承是一个“is-a”关系,而不是“has-a”关系(Animal->Human 对比 User->UserDetails)。
- 可以从基础复用代码 (人可以像所有动物一样移动)。
- 你想通过修改基础来实现对所有子类的全局性更改。(改变动物移动时的热量消耗)。
不好:
class Employee {
 constructor(name, email) {
  this.name = name;
  this.email = email;
 }
 // ...
}
// 这样不好,因为 Employees "拥有" 税务数据。EmployeeTaxData 不是属于 Employee 的一个类型
class EmployeeTaxData extends Employee {
 constructor(ssn, salary) {
  super();
  this.ssn = ssn;
  this.salary = salary;
 }
 // ...
}
好:
class Employee {
 constructor(name, email) {
  this.name = name;
  this.email = email;
 }
 setTaxData(ssn, salary) {
  this.taxData = new EmployeeTaxData(ssn, salary);
 }
 // ...
}
class EmployeeTaxData {
 constructor(ssn, salary) {
  this.ssn = ssn;
  this.salary = salary;
 }
 // ...
}
      内容版权声明:除非注明,否则皆为本站原创文章。
