背景:模块query-string例如能够将 key=value&hello=universe
解析为对象 {key: 'value', hello: 'universe'}
。但是,模块作者已决定返回的对象没有原型(prototype)。换句话说,这个“ SCSS ”对象是由 Object.create(null)
创建的。
问题:使用 parsed.hasOwnProperty('hello')
会很方便,但如果没有默认对象原型(prototype),这是不可能的。当然,可以 Object.prototype.hasOwnProperty.call(parsed, 'hello')
但我认为我们都同意这样的表达式是 kill-immediately-after-birth 丑陋的。
问题如何将无原型(prototype)对象很好地转换为具有默认对象原型(prototype)和方法,如hasOwnProperty
?此外,是否可以在不使用 the feared 的情况下完成此操作? __proto__
还是 setPrototypeOf
?
最佳答案
It would be convenient to use
parsed.hasOwnProperty('hello')
but that is not possible without the default object prototype
创建这样一个“ SCSS 对象”的全部意义在于你不能这样做 - 如果有人向你的服务器发送查询字符串 ?hasOwnProperty=oops
怎么办?
How to nicely convert the prototypeless object to have a default object prototype and methods such as
hasOwnProperty
?
不要。您应该使用带有call
的长格式,或者直接使用in
operator。这正是您所需要的:
'hello' in parsed
在 ES6 环境中,您可能还想将对象转换为适当的 Map
并使用它的 has
方法。
关于javascript - 如何从一个没有原型(prototype)的对象创建一个有默认原型(prototype)的JS对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839991/