JavaScript Object Prototypes

Every JavaScript object has a prototype, which provides shared properties and methods. Prototypes enable inheritance and avoid duplicating code across object instances.

Key Topics

Prototype Chain

Accessing a property checks the object first, then its prototype, forming a chain until Object.prototype.

let arr = [1, 2, 3];
console.log(arr.toString());

Output

> 1,2,3

Explanation: arr inherits toString() from Array.prototype, which in turn inherits from Object.prototype.

Object.prototype

The base object from which almost all objects inherit. Contains fundamental methods like hasOwnProperty().

Custom Prototypes

Define methods on a constructor's prototype property to share them among all instances without duplicating memory usage.

function Person(name) {
    this.name = name;
}
Person.prototype.greet = function() {
    console.log("Hello, " + this.name);
};
let p = new Person("Alice");
p.greet();

Output

> Hello, Alice

Explanation: The greet method is inherited from Person.prototype, so every Person instance can call it.

JavaScript Usage in DOM

DOM elements also have prototypes (e.g. HTMLElement.prototype), providing shared methods like appendChild and querySelector. You can add custom methods to your own prototypes for repeated UI logic.

<script>
function UIElement(id) {
    this.el = document.getElementById(id);
}
UIElement.prototype.show = function() {
    this.el.style.display = "block";
};
UIElement.prototype.hide = function() {
    this.el.style.display = "none";
};
</script>

Key Takeaways

  • Prototype Chain: Inheritance flows up to Object.prototype.
  • Memory Efficiency: Methods on prototypes avoid duplication.
  • DOM Integration: Extend prototypes for custom UI logic shared by instances.