如何在调用时不发送第一个参数的情况下获取默认值

时间:2018-07-10 16:31:29

标签: javascript es6-class

我想以这种方式获取输出,

Lucifer is 20 years old
Default is 20 years old

问题是,如果我将一个空字符串作为第一个参数发送,将20作为第二个参数,则会得到以下输出:

Lucifer is 20 years old
is 20 years old 

再一次,如果我只发送一个参数,例如20作为第一个参数,而没有发送第二个参数,则会得到以下输出:

Lucifer is 20 years old
20 is 20 years old

这是我的代码,构造函数是我要将参数发送到的函数:

class Person {
    constructor(name = 'Default',age=0){
        this.name = name;
        this.age = age;
    }
    getDescription() {
        return `${this.name} is ${this.age} years old`
    }
}

const me = new Person('Lucifer',20);
console.log(me.getDescription());

const meNew = new Person('',20);
console.log(meNew.getDescription());

1 个答案:

答案 0 :(得分:5)

在强制参数之前不能有可选参数。您应该更改参数的顺序,或使用配置对象:

class Person {
    constructor(options = {}) {
        this.name = options.name || 'Default';
        this.age = options.age || 20;
    }
    getDescription() {
        return `${this.name} is ${this.age} years old`
    }
}

const me = new Person({name: 'Lucifer', age: 20});
console.log(me.getDescription());

const meNew = new Person({age: 20});
console.log(meNew.getDescription());