为参数分配默认值

时间:2014-09-30 18:45:15

标签: javascript oop

我正在学习Javascript,但我发现了一个问题。我必须给定一些参数来定义构造函数。我插入它们但我想插入一个if来检查用户什么时候什么都不插入。我正在使用寄生继承模型,但我不知道如何插入此案例。这是我的构造函数的一部分:

function user(_id, userName, email, password, firstName, lastName, date_created, playlists) {

if (firstName === 'undefined') {
    firstName = userName;

}
if (lastName === 'undefined') {
    lastName = userName;
}
return {
    _id: _id,
    userName: userName,
    email: email,
    password: password,
    firstName: firstName,
    lastName: lastName,
    date_created: new Date(),
    playlists: []

};
}

假设用户不使用firstName和LastName。它将返回undefined。但我想存储一个默认值。我该怎么做?

1 个答案:

答案 0 :(得分:3)

首先,如果这是一个构造函数,你应该这样写:

function User(_id, userName, email, password, firstName, lastName, date_created, playlists) {
    this._id = _id;
    this.userName = userName;
    this.email = email;
    this.password = password;
    this.firstName =  firstName;
    this.lastName =  lastName;
    this.date_created = date_created,
    this.playlists = playlists 
} 

这样,您可以使用new关键字调用它,获取一个设置了正确值的新对象。

接下来,为了设置默认值,您可以在每个属性上使用||进行一些简短的填充。这样,只有在未提供值时才使用默认值。

function User(_id, userName, email, password, firstName, lastName, date_created, playlists) {
    this._id = _id;
    this.userName = userName;
    this.email = email;
    this.password = password;
    this.firstName =  firstName || "defaultValue";
    this.lastName =  lastName || "defaultValue";
    this.date_created = date_created || new Date(),
    this.playlists = playlists || [] 
}