Why object literal can access the property of Object's prototype?

Viewed 103

While reading Processional JavaScript for Web Developers 4th edition, I found the saying:

When defining an object via object literal notation, the Object constructor is never actually called.

But if the object literal isn't created through Object constructor, how can it access the property of Object.prototype?

Like this:

Object.prototype.a = 1
let obj = {}
console.log(obj.a)      // 1

Or can anyone tell me how the conclusion given by the book come out? I didn't find anything about this in ECMAScript specification.

1 Answers

To quote MDN

Objects are created as if a call to new Object() were made; that is, objects made from object literal expressions are instances of Object.

So, in your code obj 'automagically' becomes instance of Object.

The assignment of Object.prototype.a in your code will create a as property of everything that inherits from Object (in js that is: everything) you create subsequently.

Object.prototype.a = 'I am the one';
let obj = {};
let Constrctr = function(aa = this.a) {
  //                          ^ QED
  this.aa = aa;
  
};
let obj2 = new Constrctr();
let obj3 = new Constrctr(2);
let someArray = new Array();
let someArrayLiteral = [];
let someNumber = new Number();
let someNumberLiteral = 42;
let someRegex = new RegExp();
let someString = new String();
let someStringLiteral = "";
let someFunction = () => {};

document.querySelector('pre').innerHTML = `<h2><i>Everything</i></h2>obj.a: ${obj.a},
obj2.aa: ${obj2.aa}, 
obj2.a: ${obj2.a},
obj3.aa: ${obj3.aa},
obj3.a: ${obj3.a},
someNumber.a: ${someNumber.a},
someNumberLiteral.a: ${someNumberLiteral.a},
someArray.a: ${someArray.a},
someArrayLiteral.a: ${someArray.a},
someRegex.a: ${someRegex.a},
someString.a: ${someString.a},
someStringLiteral.a: ${someStringLiteral.a},
someFunction.a: ${someFunction.a}`;
<pre></pre>

Related