问题描述
MDN提示使用 .setPrototypeOf()
会对代码的未来性能产生不良影响。
The MDN hints that using .setPrototypeOf()
will have a bad influence on the future performance of your code.
我还读了一些关于为什么改变对象的[[Prototype]]会降低性能的问题。但是没有一个答案真正解释了在后台发生的事情。所以我想知道这是否也适用于新的对象。
I also read a few Questions about why changing the [[Prototype]] of an object will lower the performance. But none of the answers really explained whats going on in the background. So I wonder if this also applies for new Objects.
特别是我真的喜欢这样的事情:
In particular I really like to do things like this:
var MyPrototype = {
method1 : function(){...},
method2 : function(){...},
...
};
var newObject = Object.setPrototypeOf({
property : 1,
property2 : 'text'
}, MyPrototype);
很遗憾你不能用 Object.create $ c来做这件事$ c>因为它不接受普通对象文字。
Unfortunately you can't do this with Object.create
since it doesn't accept a plain object literal.
我使用 setPrototypeOf
是否也减少了执行JS引擎的性能?
Does my use of setPrototypeOf
also decrease the performance of the executing JS engine?
推荐答案
如果你担心(显然你应该......)使用<$的性能影响c $ c> Object.setPrototypeOf(),但是想让你的对象创建语法与你的代码结构类似,试试这个:
If you fear (as apparently you should..) the performance impact of using Object.setPrototypeOf()
, but want to keep your object creation syntax similar to how your code is structured, try this:
var MyPrototype = {
method1 : function(){...},
method2 : function(){...},
...
};
var newObject = Object.assign(Object.create(MyPrototype), {
property : 1,
property2 : 'text'
});
这篇关于什么是setPrototypeOf对新对象的性能影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!