Property lookup can continue through another object
Each ordinary object has an internal prototype link to another object or null. If an own property is absent, lookup can continue along that prototype chain. This delegation differs from copying every inherited property into the child.
const lessonMethods = {
describe() { return 'Lesson: ' + this.title; }
};
const lesson = Object.create(lessonMethods);
lesson.title = 'Prototypes';
console.log(lesson.describe()); // Lesson: Prototypes
console.log(Object.hasOwn(lesson, 'title')); // true
console.log(Object.hasOwn(lesson, 'describe')); // false
console.log(Object.getPrototypeOf(lesson) === lessonMethods); // truedescribe is found on the prototype, but this is the receiving lesson object when invoked as lesson.describe(). Adding an own property with the same name shadows the inherited one; it does not erase the prototype's property.
Constructor prototype versus an object's prototype
function Course(title) { this.title = title; }
Course.prototype.label = function () { return this.title; };
const course = new Course('JavaScript');
console.log(Object.getPrototypeOf(course) === Course.prototype); // true
console.log(course.label()); // JavaScriptThe .prototype property on a constructor is used for instances created with new. It is not the same concept as saying every object's property named prototype determines its own internal prototype. Class instance methods normally live on the class's prototype too.
Own-property checks
The in operator checks inherited as well as own properties. Use Object.hasOwn when only data directly on an object should count. Avoid relying on an object's own hasOwnProperty method, which an input property can shadow or a null-prototype object may not possess.
Do not modify shared built-ins
Changing Array.prototype or Object.prototype can affect unrelated code and create surprising enumeration or security behavior. Do not recursively merge arbitrary untrusted keys into object graphs without a deliberate validation strategy. Prefer explicit data schemas at boundaries.
Practice
- Add an own describe method to lesson, then remove it and observe inherited lookup resume.
- Compare Object.keys with an inherited method.
- Create an object with Object.create(null) and inspect its absent built-in prototype methods.
- Draw the chain for course through Course.prototype without using legacy __proto__ assignment.