Home > database >  Prototype as "just a plain object"
Prototype as "just a plain object"

Time:04-12

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?

CodePudding user response:

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'));

  • Related