如何使用默认原型从没有原型的对象创建JS对象? [英] How to create a JS object with the default prototype from an object without a prototype?
问题描述
背景:查询字符串模块适用于示例能够将 key = value& hello = universe
解析为对象 {key:'value',hello:'universe'}
。但是,模块作者已决定返回的对象没有原型。换句话说,这个混蛋对象是由 Object.create(null)
创建的。
Background: The module query-string is for example able to parse key=value&hello=universe
to an object {key: 'value', hello: 'universe'}
. However, the module author has decided that the returned object does not have a prototype. In other words, this "bastard" object is created by Object.create(null)
.
问题:使用 parsed.hasOwnProperty('hello')
会很方便,但如果没有默认对象原型,这是不可能的。当然,可以 Object.prototype.hasOwnProperty.call(已解析,'hello')
但我认为我们都同意这样的表达式是kill-immediately-after- after-出生难看。
Problem: It would be convenient to use parsed.hasOwnProperty('hello')
but that is not possible without the default object prototype. Of course, one could Object.prototype.hasOwnProperty.call(parsed, 'hello')
but I think we can all agree that such an expression is kill-immediately-after-birth ugly.
问题:如何很好地将无原型对象转换为默认对象原型和方法,例如 hasOwnProperty
?另外,这可以在不使用担心 __ proto __
或 setPrototypeOf
?
Question: How to nicely convert the prototypeless object to have a default object prototype and methods such as hasOwnProperty
? Additionally, can this be done without using the feared __proto__
or setPrototypeOf
?
推荐答案
使用
parsed.hasOwnProperty('hello')
会很方便,但这不是可能没有默认对象原型
It would be convenient to use
parsed.hasOwnProperty('hello')
but that is not possible without the default object prototype
创建这样一个混蛋对象的全部意义在于你不能这样做 - 如果有人怎么办?发送查询字符串?hasOwnProperty = oops
到您的服务器?
The whole point of creating such a "bastard object" is that you cannot do that - what if someone sent a query string ?hasOwnProperty=oops
to your server?
如何正确将无原型对象转换为默认对象原型和方法,如
hasOwnProperty
?
不要。您应该使用长格式与调用
,或者只是去 在
运算符中你需要什么:
Don't. You should either use the long form with call
, or just go for the in
operator which does exactly what you need:
'hello' in parsed
在ES6环境中,您可能还希望将对象转换为正确的 Map
并使用它 has
方法。
In an ES6 environment, you might also want to convert the object to a proper Map
and use it has
method.
这篇关于如何使用默认原型从没有原型的对象创建JS对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!