如何在调用时不发送第一个参数的默认值

Luc*_*fer 1 javascript es6-class

我想以这种方式得到输出,

Lucifer is 20 years old
Default is 20 years old
Run Code Online (Sandbox Code Playgroud)

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

Lucifer is 20 years old
is 20 years old 
Run Code Online (Sandbox Code Playgroud)

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

Lucifer is 20 years old
20 is 20 years old
Run Code Online (Sandbox Code Playgroud)

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

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());
Run Code Online (Sandbox Code Playgroud)

mea*_*gar 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());
Run Code Online (Sandbox Code Playgroud)