I had read somewhere that literal objects do not have prototype property like function objects (or constructors).
This sounds like it's referring to the property named .prototype
, which is true. A function
and a class
will automatically receive a .prototype
property, which contains one property (constructor
, pointing to the class/function itself) and inheriting from Object.prototype
.
The statement in your question is true. Only callable class-like objects - classes and function
s - automatically receive these sorts of properties. Other objects do not:
class Foo {
}
function Foo2() {
}
const obj = {};
console.log(
Foo.prototype,
Foo2.prototype,
obj.prototype
);
Regarding the code in your question, using __proto__
is permitted, but it's deprecated. As MDN says:
Warning: While Object.prototype.__proto__
is supported today in most browsers, its existence and exact behavior has only been standardized in the ECMAScript 2015 specification as a legacy feature to ensure compatibility for web browsers. For better support, it is recommended that Object.getPrototypeOf()
be used instead.
Object.getPrototypeOf
should be preferred nowdays.
i.e. when we do "new SomeFunctionObject()"
When you create an instance with new
, the internal prototype of the new instance will (usually) be same object as the .prototype
property of the constructor. That is, with the following code:
class Foo {
// anything
}
const f = new Foo();
the internal prototype of the f
instance will be the same object as Foo.prototype
.
class Foo {
// anything
}
const f = new Foo();
console.log(
Object.getPrototypeOf(f) === Foo.prototype,
f.__proto__ === Foo.prototype,
);
The only time where the internal prototype of an instance will not be the same as the constructor's .prototype
would be when the constructor explicitly returns an object, which is somewhat unusual.
class Foo {
constructor() {
return {};
}
}
const f = new Foo();
console.log(
Object.getPrototypeOf(f) === Foo.prototype,
f.__proto__ === Foo.prototype,
);