javascript - JavaScript 中长构造函数的最佳实践

标签 javascript oop object constructor

我正在创建具有很多属性的对象,我对实例化它们的最佳实践很好奇。拥有非常长的构造函数似乎很糟糕(实例化新对象并不好玩)。

function Book(title, author, pages, chapters, publisher, datePublished, authorHometown, protagonistFavoriteColor) {
  this.title = title;
  this.authorpages = authorpages;
  this.pages = pages;
  this.chapters = chapters;
  this.publisher = publisher;
  this.datePublished = datePublished;
  this.authorHometown = authorHometown;
  this.protagonistFavoriteColor = protagonistFavoriteColor;
}

// not reliable to remember how to order params
var rc = new Book("Robinson Crusoe", "Daniel Defoe", 342, 16, ...);

我想知道我是否应该只在构造函数中设置三个重要属性(例如标题、作者和页面),然后为其余部分编写单独的 setter 。或者为了保持一致性我应该只使用 setter 吗?如果以这种方式设置是最好的路径,那么 JS 中是否有一种好的方法来强制调用这些方法(有点像 Java 中的接口(interface))?

function Book (title, author, pages){
  this.title = title;
  this.author = author;
  this.pages = pages;
  this.chapters = null;
  this.publisher = null;
  this.datePublished = null;
  this.authorHometown = null;
  this.protagonistFavoriteColor = null;
}

var rc = new Book("Robinson Crusoe", "Daniel Defoe", 342);
rc.setChapters(16);
rc.setPublisher("John Smith Co.");
rc.setDatePublished("04-25-1719");
rc.setAuthorHometown("London");
rc.setProtagonistFavoriteColor("lilac");
// we'd also want to mandate that these setters be called so nothing is left null

最后,将一个对象传递给我的构造函数并对其进行解构会完全破坏构造函数的 pt 吗?

最佳答案

最佳实践是将定义属性的对象传递给构造函数:

function Book(props) {
  // create variables out of object (if you need to)
  const {
    title,
    author,
    pages,
    chapters,
    publisher,
    datePublished,
    authorHometown,
    protagonistFavoriteColor
  } = props;

  // assign properties to instance object
  Object.assign(this, props);
}

const rc = new Book({
  title: "Robinson Crusoe",
  author: "Daniel Defoe",
  pages: 342,
  chapters: 16,
  // rest of properties
});

console.log(rc);

JSFiddle 演示:https://jsfiddle.net/Lr6umykn/3/

关于javascript - JavaScript 中长构造函数的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456801/

相关文章:

c++ - 面向对象编程,使用静态函数统计对象

javascript - 始终使用 UTC+0 - 使用 javascript/angularjs 修复客户端浏览器上的自定义时区

javascript - Dropzone Rails 505 错误

javascript - 使用数组时div不会显示

javascript - window.speechSynthesis.getVoices() 在 macOS safari 15.4 上返回空数组

javascript - 为什么将联系人添加到数组的方法不起作用?

javascript - 如何在不使用 marquee 标签的情况下滚动图像? Javascript、jquery 或 css 任何东西

javascript - 如何在 javascript 中扩充父类(super class)中的方法

codeigniter - 在 codeigniter 对象上的 isset()

python - 为什么 'is' 运算符说这些方法不一样?