Skip to content

08. Prototypes and Inheritance

idavidov13 edited this page Feb 13, 2024 · 2 revisions

Internal Object Properties

Internal Properties

Every object field has four properties:

  • Enumerable - can access all of them using a for…in loop

Enumerable properties are returned using Object.keys method

  • Configurable - can modify the behavior of the property

You can delete only configurable properties

  • Writable - can modify their values and update a property just by assigning a new value to it
  • Value

Inheritance

Types of Inheritance

Single Inheritance (A=>B)

Multilevel Inheritance (A=>B=>C)

Hierarchical Inheritance (A=>B A=>C)

Multiple Inheritance - Not supported in JS with classes, but works with composition - (A=>C B=>C)

The Prototype

What is a Prototype?

Every object in JS has a prototype (template)

  • Internally called proto in browsers and NodeJS
  • Properties lookup follows the prototype chain

Obtained with Object.getPrototypeOf(obj)

Reference to another objects

  • Objects are not separate and disconnected, but linked

Objects inherit properties and methods from a prototype

The prototype property allows you to add new properties to object constructors

Class Inheritance

Traditional Classes

Classes are a design pattern

Classes mean - creating copies

  • When instantiated – a copy from class to instance
  • When inherited – a copy from parent to child

Class inheritance is a powerful tool, but has many drawbacks and limitation

  • Composition should be preferred whenever possible!

Class Inheritance

Classes can inherit (extend) other classes

  • Child class inherits data + methods from its parent

Child class can:

  • Add properties (data)
  • Add / replace methods
  • Add / replace access properties

Use the keyword extends

Clone this wiki locally