Search⌘ K
AI Features

Member Injection: Class's Prototype and Property

Explore how to inject methods into a class’s prototype to make them available across all instances. Learn to use defineProperty to add properties with getters and setters, and understand the impact of injection on instances, enhancing your metaprogramming skills.

Injecting a method into a class’s prototype

We injected the reverse() method into one single instance in the previous lesson. Let’s make that method available in all instances. It’s not much work; the key is to inject the method into the class’s prototype instead of into the class itself. This is because instances of a class share a common prototype, and JavaScript uses an object’s prototype chain to look for properties—see Understanding Prototypal Inheritance.

Example

Let’s create a few instances of String, one using new and the others without it. When ...