gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:41:43 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com