类构造函数中options对象的默认值 [英] Default value for options object in class constructor

查看:102
本文介绍了类构造函数中options对象的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类,我想为值设置一些默认选项,以防用户不提供任何参数.最近,我从采用多个参数的构造函数转到了一个对象,因为我相信当用户创建类的新实例时,它有助于提高可读性.

I've created a class and I would like to set some default options for values in case the user does not supply any arguments. I recently went from a constructor that took multiple parameters to an object because I believe it helps readability when the user is creating a new instance of the class.

这是我之前的操作方式:

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"无法读取未定义的属性名称" ,即使我认为我将默认设置为"Joe"

In reality, my class has more parameters than that and the readability when using it becomes tough. So to solve this I switched to an options object that works much better but I can't seem to put default values. When I try to use this.name it says this.name = options.name || "Joe" Cannot read property 'name' of undefined even though I thought I set the default to "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();

推荐答案

您可以设置选项的默认值,即 {} .

You could either set a default value for options, i.e {}.

class User {
    constructor(options = {}) {
        this.name = options.name || "Joe";
        this.age = options.age || 47;
    }
}

或首先检查选项是否为真,然后访问该值.

or first check for options to be truthy and then access the value.

class User {
    constructor(options) {
        this.name = options && options.name || "Joe";
        this.age = options && options.age || 47;
    }
}

这篇关于类构造函数中options对象的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆