3.13 Objects and Classes
Arrays are great for "a list of similar values," but some things are more like "a single whole with many properties": a person has a name, age, email; a car has a brand, color, speed. This kind of data is most naturally an object.
The lab below has two tabs: first an "object literal," then how a "class" mass-produces objects.
Loading interactive lab...
Objects: store data as "key-value pairs"
Objects use braces {} holding a set of key: value:
js
const person = {
name: "Leaf",
age: 18,
isStudent: true,
};Access properties with a dot:
js
person.name // "Leaf"
person.age // 18
person.age = 19; // change a property
person.email = "[email protected]"; // add a propertyLoading concept check...
Objects can hold functions (methods)
An object's value can be a function; such a function is a method:
js
const dog = {
name: "Rex",
bark: function () {
return this.name + " says woof!";
},
};
dog.bark(); // "Rex says woof!"this refers to "the current object," so this.name is dog.name.
Classes: a "template" to mass-produce objects
To build many objects of the same shape (100 dogs), hand-writing each is tedious. A class is a "blueprint," and new builds any number of instances from it:
js
class Dog {
constructor(name) { // runs automatically on creation
this.name = name; // each instance stores its own name
}
bark() { // a method, shared by all instances
return this.name + " says woof!";
}
}
const rex = new Dog("Rex");
const bobby = new Dog("Bobby");
rex.bark(); // "Rex says woof!"
bobby.bark(); // "Bobby says woof!"class: defines the template.
constructor: a special method run automatically onnew, to initialize each instance's data.
new Dog("Rex"): builds a concrete instance from the template.
this: refers to the current instance. Each instance'sthis.namediffers and is independent.
Loading concept check...
Note
Object vs array — which to use? When data is "a list of similar things distinguished by position" (1st, 2nd), use an array; when data is "one thing's many properties distinguished by name" (name, age), use an object. They also nest: an array holding many objects is the most common front-end data structure.
Loading practice...