Member Injection: Injecting Multiple Properties
Let's now discuss how to inject multiple properties in one shot into the class.
We'll cover the following
Instead of adding one property at a time, we can add multiple properties in one shot—let’s explore how. Along the way, you’ll see how to inject read-write properties. The properties we injected so far were read-only since we created only getters. Next, we’ll create setters as well, so the properties may not only be read but also modified.
Injecting into Array
's class
First, let’s think of a couple of useful properties to add to an existing class. The Array
class in JavaScript provides a number of nice methods, but there’s no elegant way to access the first or last element. We will inject a first
and a last
property into the Array
class. For this example, let’s start with an array of language names:
const langs = ['JavaScript', 'Ruby', 'Python', 'Clojure'];
Get hands-on with 1200+ tech skills courses.