How to create a JS object with the default prototype from an object without a prototype?

烂漫一生 提交于 2019-12-01 18:38:10

It would be convenient to use parsed.hasOwnProperty('hello') but that is not possible without the default object prototype

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?

How to nicely convert the prototypeless object to have a default object prototype and methods such as 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

In an ES6 environment, you might also want to convert the object to a proper Map and use it has method.

I wouldn't recommend changing the prototype of a third party package, it may be frozen and prone to runtime errors. I'd either use the built-in in operator as @Bergi suggested or the ES6 Reflect API.

const _ = console.info

const parsed = (
  { __proto__: null
  , foo: 'fu'
  , bar: 'bra'
  }
)

_('foo' in parsed) // true

_('fu' in parsed) // false


/** ES6 (fully supported in current browsers) */

_(Reflect.has(parsed, 'foo')) // true

_(Reflect.has(parsed, 'fu')) // false

I can't say I've ever done this before, but here's one way to do it

let bastard = Object.create(null);
bastard.father = 'vader';

let adopted = Object.assign({}, bastard);
console.log(adopted.hasOwnProperty('father')); // => true

setPrototypeOf() is nothing to be feared of, yet without it you might do as follows;

var o1 = Object.create(null),
    o2;
o1.test = "42";
o2 = Object.assign({},o1);
console.log(o2.test);
console.log(o2.constructor.prototype);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!