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

Background: The query-string module , for example, is able to parse key=value&hello=universeon an object {key: 'value', hello: 'universe'}. However, the author of the module decided that the returned object does not have a prototype. In other words, this bastard object is created Object.create(null).

Problem: It would be convenient to use parsed.hasOwnProperty('hello'), but this is not possible without a prototype of the default object. Of course, it would be possible Object.prototype.hasOwnProperty.call(parsed, 'hello'), but I think we can all agree that such an expression kills-right after birth is ugly.

Question: How to convert a prototype object well in order to have a default prototype object and methods like hasOwnProperty? Also, can this be done without the use of a feared __proto__ or setPrototypeOf?

+4
source share
4 answers

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

The whole point of creating such a “bastard object” is that you cannot do this — what if someone sent a query string ?hasOwnProperty=oopsto your server?

How to convert a prototype object well to have a default prototype object and methods like hasOwnProperty?

. call, in, , :

'hello' in parsed

ES6 Map has.

+4

, . in, @Bergi, API- ES6 Reflect.

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
Hide result
+2

, - ,

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

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

setPrototypeOf() , :

var o1 = Object.create(null),
    o2;
o1.test = "42";
o2 = Object.assign({},o1);
console.log(o2.test);
console.log(o2.constructor.prototype);
Hide result
0

Source: https://habr.com/ru/post/1656633/


All Articles