Introduction to Object Prototypes

All objects in JavaScript have an internal property called the prototype. Prototypes are used in JavaScript to reuse code and combine objects. This section will help you understand how prototype object chains allow objects to inherit features from one another. It will also explain how the prototype property is used to add methods to constructors.

Shadowing properties

What happens if you define a property in an object, when a property with the same name is defined in the object's prototype? Let's see:

const myDate = new Date(1995, 11, 17);

console.log(myDate.getYear()); // 95

myDate.getYear = function () {
  console.log("something else!");
};

myDate.getYear(); // 'something else!'

This should be predictable, given the description of the prototype chain. When we call getYear() the browser first looks in myDate for a property with that name, and only checks the prototype if myDate does not define it. So when we add getYear() to myDate, then the version in myDate is called.

This is called "shadowing" the property.