Using the Fluent Interface Pattern to Build Objects in JavaScript

栏目: IT技术 · 发布时间: 4年前

内容简介:There are many ways to create new JavaScript objects. In this post, we’ll use theIn the following example, we create aFinally, we have a

There are many ways to create new JavaScript objects. In this post, we’ll use the fluent interface pattern! In the fluent interface pattern, we use classes with defined methods to add attributes to our object.

In the following example, we create a PersonBuilder class. In the constructor , we create an empty person property. Then, we have some additional methods called withName and withAge that allow us to give our person a name and age, respectively.

Finally, we have a build method. This just returns our person object, signifying that we’re done building.

class PersonBuilder {
  constructor() {
    this.person = {};
  }
  withName(name) {
    this.person.name = name;
    return this;
  }
  withAge(age) {
    this.person.age = age;
    return this;
  }
  build() {
    return this.person;
  }
}

Note that we return this in the withName and withAge methods—this returns the current instance, allowing us to continue to chain methods.

The implementation of our class ends up being something like this:

const person = new PersonBuilder()
  .withName('Daffodil')
  .withAge(25)
  .build();
console.log(person);
// { name: "Daffodil", age: 25 }

And that’s it, we now have a person object!

Why Build Objects This Way?

The fluent interface pattern can definitely be verbose, but one nice thing about it is that it makes it pretty hard to set an incorrect property on your object—you can only set object props by using the methods on your class. This can be especially handy if your object has a lot of properties, or if you need a handy way to generate a bunch of different objects to a specification (e.g., for test case generation).


以上所述就是小编给大家介绍的《Using the Fluent Interface Pattern to Build Objects in JavaScript》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

图解CIO工作指南(第4版)

图解CIO工作指南(第4版)

[日] 野村综合研究所系统咨询事业本部 / 周自恒 / 人民邮电出版社 / 2014-3 / 39.00

《图解CIO工作指南(第4版)》是一本实务手册,系统介绍了企业运用IT手段提高竞争力所必需的管理方法和实践经验,主要面向CEO或CIO等企业管理人士。 《图解CIO工作指南(第4版)》分为三个部分。第1部分的主题为IT管理,着重阐述运用IT技术提高企业竞争力所必需的所有管理业务,具体包括制定作为企业方针的IT战略,以及统筹执行该战略时与IT相关的人力、物力、财力、风险等要素在内的一系列管理业......一起来看看 《图解CIO工作指南(第4版)》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具