JS: Property key "prototype"
What is the property key named "prototype"
The property key "prototype" is used by the “new” operator
as the parent object for objects it creates.
That is, when new f(), the result object's parent is f.prototype.
(note, only if f does not have return statement, or it does but does not return a object type.)
// create a constructor function Cow() {} // js auto creates a property string key "prototype" console.assert(Object.hasOwn(Cow, "prototype")); // create a object const jj = new Cow(); // check the parent object is Cow.prototype console.assert( Reflect.getPrototypeOf(jj) === Cow.prototype, );
Every function by keyword function has a property key "prototype"
Every function defined by keyword function has a property key "prototype", by spec, automatically created by JavaScript.
// every function defined by keyword function has a property key "prototype" function Cow() {} console.assert( Object.hasOwn(Cow, "prototype"), ); // arrow function does not console.assert( Object.hasOwn((x) => (x + 1), "prototype") === false, );
Value of property key "prototype"
For user-defined function f, the value of f.prototype by default is a newly created data object {"constructor":f}.
// Default Value of Property Key "prototype" function Cow() {} console.log(Cow.prototype); // {} // empty because the property we are looking for is not enumerable // force show all properties console.log(Reflect.ownKeys(Cow.prototype)); // [ "constructor" ] // show the value console.log(Cow.prototype.constructor); // [Function: Cow] console.log( (Cow.prototype.constructor) === Cow, ); // true
Attributes of default value of property key "prototype"
function Cow() {} // show attributes of Cow.prototype console.log( Reflect.getOwnPropertyDescriptor( Cow.prototype, "constructor", ), ); /* { value: [Function: Cow], writable: true, enumerable: false, configurable: true } */
Parent is object.prototype
function Cow() {} // show its parent console.assert( Reflect.getPrototypeOf(Cow.prototype) === Object.prototype, );
Property key "prototype" of standard object's constructors
Standard object's constructors all have property key "prototype".
// standard object's constructors all have property key "prototype" [Object, Function, Array, Date, RegExp] .forEach((x) => { console.assert( Object.hasOwn(x, "prototype"), ); });
For any JavaScript's buildin constructor C, the parent of new C(…) is always C.prototype.
// For any standard buildin constructor B, the parent of new B(…) is always B.prototype. [Object, Function, Array, Date, RegExp] .forEach((x) => { console.assert( Reflect.getPrototypeOf(Reflect.construct(x, [])) === x.prototype, ); });
Standard constructor's prototype property cannot be changed
Standard constructor's prototype property cannot be changed, because its writable attribute is false.
console.assert( Reflect.getOwnPropertyDescriptor(Array, "prototype").writable === false, );