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

前端 未结 4 2230
傲寒
傲寒 2021-01-19 22:58

Background: The module query-string is for example able to parse key=value&hello=universe to an object {key: \'value\', hello: \'univ

4条回答
  •  醉酒成梦
    2021-01-19 23:28

    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

提交回复
热议问题