[英]TypeScript: Set Object.prototype with spread operator
Using the spread operator is a succinct way to compose an object consisting of an aggregation of other objects' properties. 使用散布运算符是一种精简的方式来构成一个由其他对象属性的集合组成的对象。
But is there succinct and performant way to set the prototype of an object with the spread operator? 但是,是否有使用精简高效的方法使用传播算子设置对象原型的方法?
Currently I have: 目前我有:
const result = Object.assign(Object.create(EmailCampaign.prototype), properties)
. 。 .
。 .
。 which spreads the properties returned from a database query into an object with the
EmailCampaign
prototype. 这
EmailCampaign
数据库查询返回的属性传播到使用EmailCampaign
原型的对象中。 Is there a way to set the object prototype with the spread operator? 有没有一种方法可以使用传播算子设置对象原型?
This would be possible: 这将是可能的:
const result = Object.setPrototypeOf({...properties}, EmailCampaign.prototype);
. 。 .
。 however it is inadvisable with regards to performance to set the prototype of an object after instantiation.
但是,在性能方面,不建议在实例化后设置对象的原型。 I'm looking for another way, if one exists.
我正在寻找另一种方式(如果存在)。
Using Object.assign
+ Object.create
is the proper and performant solution. 使用
Object.assign
+ Object.create
是正确且Object.create
的解决方案。 You should use it. 您应该使用它。 If you want to make it more concise, use a helper function that combines the two.
如果要使其更简洁,请使用结合了两者的帮助器功能。
That said, calling Object.setPrototypeOf
on an object literal is not that slow, as the object was not yet used elsewhere. 这就是说,调用
Object.setPrototypeOf
对象文本上不慢 ,因为对象尚未在其他地方使用。
Is there a way to set the object prototype with the spread operator?
有没有一种方法可以使用传播算子设置对象原型?
Well if you want to use an officially deprecated feature, you can use the __proto__
property in an object intialiser: 好吧,如果要使用正式弃用的功能,可以在对象初始化器中使用
__proto__
属性 :
const result = {__proto__: EmailCampaign.prototype, ...properties};
So yes, it's possible, but I would definitely not recommend it. 是的,这是可能的,但我绝对不会推荐它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.