我创建了一个类,我想为值设置一些默认选项,以防用户不提供任何参数。我最近使用了一个将多个参数传递给一个对象的构造函数,因为我相信当用户创建该类的新实例时,它有助于提高可读性。
这是我之前的做法:
module.exports = class User {
constructor(name = "Joe", age = 47) {
this.name = name;
this.age = age;
}
}
const User = require("./user");
const user = new User(); // Defaults to "Joe" and 47
事实上,我的类有更多的参数,并且使用它时的可读性变得很困难。因此,为了解决这个问题,我切换到了一个效果更好的选项对象,但我似乎无法设置默认值。当我尝试使用时this.name
它说this.name = options.name || "Joe" Cannot read property 'name' of undefined
即使我认为我将默认设置为“Joe”
我现在是这样做的:
module.exports = class User {
constructor(options) {
this.name = options.name || "Joe";
this.age = options.age || 47;
}
}
const User = require("./user");
const user = new User();
你实际上只需要一条线:
const defaultUser = {
name: "Joe",
age: 47
};
module.exports = class User {
constructor(options) {
Object.assign(this, defaultUser, options)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)