Javascript JS:使用键值对的构造函数的性能
在JavaScript中的对象构造函数内部使用对象文本是否会对性能产生负面影响 例如:Javascript JS:使用键值对的构造函数的性能,javascript,performance,constructor,associative-array,key-value,Javascript,Performance,Constructor,Associative Array,Key Value,在JavaScript中的对象构造函数内部使用对象文本是否会对性能产生负面影响 例如: class Thingy { constructor(props) { if (!props) { props = {}; } // defaults this.name = ''; this.amount = 0; for (let key in props) {
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);
显然,这是一种使用构造函数的非标准且更复杂的方法,但它会降低性能吗?检查任何键是否无效(并抛出),然后只使用
对象可能会容易得多。分配在这里您不应该关心性能。如果您这样做了(您没有这样做),请使用jsperf来回答您的问题。不相关,这看起来像一个坏模式,这里不需要循环或类。使用默认参数是更好的模式:constructor(props={}){/*…*/}
不要为此使用类。这会让你的api变得糟糕。只需使用对象。没有人想导入和实例化您的无行为类