2024-05-06 20:40:05 +00:00
|
|
|
---
|
2024-10-30 17:34:11 +00:00
|
|
|
date: 2020-10-08
|
2024-05-06 20:40:05 +00:00
|
|
|
id: 7a97acf5-38db-40c9-b714-4293d88aa113
|
|
|
|
title: JavaScript Class Notation
|
|
|
|
---
|
|
|
|
|
|
|
|
# Introduction
|
|
|
|
|
|
|
|
By convention, the names of constructors are capitalized so that they
|
|
|
|
can easily be distinguished from other functions. Thanks to [ECMAScript
|
|
|
|
2015](https://ecma-international.org/ecma-262/6.0/) above can be
|
|
|
|
achieved with a saner notation:
|
|
|
|
|
|
|
|
# Example
|
|
|
|
|
|
|
|
``` javascript
|
|
|
|
class Rabbit {
|
|
|
|
constructor(type) {
|
|
|
|
this.type = type;
|
|
|
|
}
|
|
|
|
speak(line) {
|
|
|
|
console.log(`The ${this.type} rabbit says '${line}'`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let killerRabbit = new Rabbit("killer");
|
|
|
|
let blackRabbit = new Rabbit("black");
|
|
|
|
|
|
|
|
killerRabbit.speak("I want blood!");
|
|
|
|
blackRabbit.speak("For some reason I appreciate Tyler Perry movies");
|
|
|
|
```
|
|
|
|
|
|
|
|
If one **must** one can also use `class` in expressions:
|
|
|
|
|
|
|
|
``` javascript
|
|
|
|
let object = new class { getWord() { return "hello"; } };
|
|
|
|
console.log(object.getWord());
|
|
|
|
```
|