Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prototype as "just a plain object"

I always thought that a prototype had some magic around it, but it seems that a prototype is actually just an object attached to a function. As an example:

function someMethod() {};

function Person(name) {
    Object.assign(this, {name});
}
Person.prototype.number = 4;
Person.prototype.letter = "a";
Person.prototype.method = someMethod;

let obj = {
    number:4, 
    letter:'a',
    method: someMethod
};

console.log(`\
${Object.entries(Person.prototype).toString()}
${Object.entries(obj).toString()}
${Object.entries(Person.prototype).toString() == Object.entries(obj).toString()}\
`);

Is that more or less a correct understanding of what the prototype is? Or does any other machinery go on behind the scenes that the obj in the above example does not include?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A .prototype object is indeed just an ordinary object. It is used in prototype chains like any other object can be used in them.

The only "magic" behind implicitly created .prototype objects on functions is that they have a non-enumerable .constructor property that points back to the function.

function Person() {}
let obj = {};

console.log(Object.hasOwn(obj, 'constructor'));
console.log(Object.hasOwn(Person.prototype, 'constructor'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading