Member Injection: Class's Prototype and Property

Learn how to inject members into the class's prototype. Let’s also discuss the method for injecting a property into single and multiple instances.

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 we inject a method into the String class’s prototype, all these instances will have it.

Get hands-on with 1200+ tech skills courses.