Using `super()` when extending `Object`

  • A+
Category:Languages

I'm creating a class that extends Object in JavaScript and expect super() to initialise the keys/values when constructing a new instance of this class.

class ExtObject extends Object {   constructor(...args) {     super(...args);   } }  const obj = new Object({foo:'bar'}); console.log(obj); // { foo: 'bar' }  const ext = new ExtObject({foo:'bar'}); console.log(ext); // ExtObject {}  console.log(ext.foo); // undefined

Why isn't foo defined as 'bar' on ext in this example?

 


Because Object's constructor returns value.
See spec

15.2.2.1 new Object ( [ value ] )
When the Object constructor is called with no arguments or with one argument value, the following steps are taken:
...
8. Return obj.

class ExtObject extends Object {   constructor(...args) {     return super(...args);   } }  const obj = new Object({foo:'bar'}); console.log(obj); // { foo: 'bar' }  const ext = new ExtObject({foo:'bar'}); console.log(ext); // { foo: 'bar' }  console.log(ext.foo); // bar

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: