在JavaScript中使用对象构造函数的对象常量 是否会对性能产生负面影响?
例如:
class Thingy {
constructor(props) {
if (!props) {
props = {};
}
// defaults
this.name = '';
this.amount = 0;
for (let key in props) {
let value = props[key];
switch (key) {
case 'name':
this.name = value;
break;
case 'amount':
this.amount = value;
break;
...
default:
throw `Invalid property ${key}`;
}
}
}
...
}
let thingy1 = new Thingy({
name: 'The Thing',
amount: 6
});
let thingy2 = new Thingy({
amount: 4,
name: 'Another Thing'
});
这样做的目的是使与默认方法相比更容易查看将哪些值附加到哪些属性,以及能够混合传递的属性顺序(甚至省略某些属性):
class Thingy {
constructor(name, amount) {
this.name = name;
this.amount = amount;
}
...
}
let thingy1 = new Thingy('The Thing', 6);
显然,这是使用构造函数的非标准且更复杂的方法,但是会降低性能吗?