Classes are a tool that developers use to quickly produce similar objects.
let halley = {
_name: 'Halley',
_behavior: 0,
get name() {
return this._name;
},
get behavior() {
return this._behavior;
},
incrementBehavior() {
this._behavior++;
}
}
Now, imagine you own a dog daycare and want to create a catalog of all the dogs who belong to the daycare. Instead of using the syntax above for every dog that joins the daycare, we can create a Dog class that serves as a template for creating new Dog objects. For each new dog, you can provide a value for their name.
As you can see, classes are a great way to reduce duplicate code and debugging time.
JavaScript calls the constructor() method every time it creates a new instance of a class.
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
const halley = new Dog('Halley'); // Create new Dog instance
console.log(halley.name); // Log the name value saved to halley
// Output: 'Halley'
Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting.
Public instance fields are added with Object.defineProperty() either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass.
class ClassWithInstanceField {
instanceField = 'instance field';
}
const instance = new ClassWithInstanceField();
console.log(instance.instanceField); // "instance field"
위에서 볼수 있듯이 인스턴스 객체에서도 해당 필드를 접근 할수 있다.
When multiple classes share properties or methods, they become candidates for inheritance — a tool developers use to decrease the amount of code they need to write.
With inheritance, you can create a parent class (also known as a superclass) with properties and methods that multiple child classes (also known as subclasses) share. The child classes inherit the properties and methods from their parent class.
If we were to abstract the shared properties of dog and cat classes into one parent class:
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
Now that we have these shared properties and methods in the parent Animal class, we can extend them to the subclass, Cat:
class Cat extends Animal {
constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
get usesLitter() {
return this._usesLitter;
}
}
benefits (time saved, readability, efficiency) of inheritance grow as the number and size of your subclasses increase.
One benefit is that when you need to change a method or property that multiple classes share, you can change the parent class, instead of each subclass.
Now that we’ve abstracted animal daycare features, it’s easy to see how you can extend Animal to support other classes, like Rabbit, Bird or even Snake.
Sometimes you will want a class to have methods that aren’t available in individual instances, but that you can call directly from the class.
Take the Date class, for example — you can both create Date instances to represent whatever date you want, and call static methods, like Date.now() which returns the current date, directly from the class. The .now() method is static, so you can call it directly from the class, but not from an instance of the class.
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0;
}
static generateName() {
const names = ['Angel', 'Spike', 'Buffy', 'Willow', 'Tara'];
const randomNumber = Math.floor(Math.random()*5);
return names[randomNumber];
}
}
console.log(Animal.generateName()); // returns a name
const tyson = new Animal('Tyson');
tyson.generateName(); // TypeError
I wasn't aware of this before, but you can use super to call parent class's static function.
class Rectangle {
static logNbSides() {
return 'I have 4 sides';
}
}
class Square extends Rectangle {
static logDescription() {
return super.logNbSides() + ' which are all equal';
}
}
Square.logDescription(); // 'I have 4 sides which are all equal'