您可以使用ES6中引入的对象分解来归档所需的行为:reference.TypeScript能够将此功能与ES5一起传输到较旧的浏览器.然而,从ES6开始,这也是完全有效的JavaScript.
基本上,它看起来是这样的:constructor({ year, month, day})
,并被调用,例如,作为new Bar({ year: 2017 })
.然后,您可以访问year
作为构造函数中的变量,例如,分配this.year = year
.
更有趣的是default values的用法,例如.
constructor({ year = new Date().getFullYear(),
month = new Date().getMonth(),
day = new Date().getDay()
} = {})
它允许分别使用0、1、2或3个参数调用构造函数(请参见下面的代码片段).
有点神秘的= {}
适用于在没有任何参数的情况下创建新实例的情况.首先,{}
被用作参数对象的默认值.然后,由于缺少year
,将分别为月份和日期添加该值的默认值.
使用TypeScript时,当然可以添加额外的打字,
constructor({ year = new Date().getFullYear(),
month = new Date().getMonth(),
day = new Date().getDay()
}: { year?: number, month?: number, day?: number } = {}) {
...
}
尽管这really个看起来很神秘.
class Bar {
constructor({ year, month, day }) {
this.year = year;
this.month = month;
this.day = day;
}
log () {
console.log(`year: ${this.year}, month: ${this.month}, day: ${this.day}`);
}
}
new Bar({ day: 2017 }).log();
class Foo {
constructor({ year = new Date().getFullYear(),
month = new Date().getMonth(),
day = new Date().getDay()
} = {}) {
this.year = year;
this.month = month;
this.day = day;
}
log () {
console.log(`year: ${this.year}, month: ${this.month}, day: ${this.day}`);
}
}
console.log('with default value:');
new Foo().log();
new Foo({ day: 2 }).log();
new Foo({ day: 2, month: 8 }).log();
new Foo({ year: 2015 }).log();