Jer*_*emy 7 javascript oop constructor object
我正在创建具有大量属性的对象,我对实例化它们的最佳实践感到好奇.看起来真的很长的构造函数(实例化新对象并不好玩)似乎很糟糕.
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, ...);Run Code Online (Sandbox Code Playgroud)
我想知道是否应该在构造函数中设置三个重要的属性(egtitle,author和pages),并为其余部分编写单独的setter.或者为了保持一致,我应该只使用setter吗?如果设置这种方式是最好的方法,JS是否有一种很好的方法来强制要求调用这些方法(类似于Java中的接口)?
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 nullRun Code Online (Sandbox Code Playgroud)
最后,将一个对象传递给我的构造函数并将其解构完全失败了构造函数的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);
Run Code Online (Sandbox Code Playgroud)
JSFiddle 演示:https://jsfiddle.net/Lr6umykn/3/