Skip to content

Writing an Example Class

Now let's write a class in a separate file. We will use some really useful proposals like the nullish coalescing operator, string templates, private class properties or class getter and setter. All these proposals will be transpiled into JavaScript that runs in mostly every relevant browser out there:

src/amazing-button.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
export default class {
  #maximumNumber = 9;
  #button;
  get maximumNumber() {
    return this.#maximumNumber;
  }
  set maximumNumber(value) {
    this.#maximumNumber = value;
    this.#button.innerHTML = `Show number from 1 to ${this.#maximumNumber}`;
  }
  constructor(element) {
    element.style.border = "1px solid red";
    element.style.textAlign = "center";
    this.#button = document.createElement("button");
    this.#button.innerHTML = `Show number from 1 to ${this.#maximumNumber}`;
    this.#button.style.marginTop = "20px";
    this.#button.addEventListener("click", () => {
      resultDiv.innerHTML = Math.floor(Math.random() * this.#maximumNumber);
    });
    element.appendChild(this.#button);
    let resultDiv = document.createElement("div");
    resultDiv.style.border = "1px solid blue";
    resultDiv.style.margin = "20px";
    resultDiv.innerHTML = "No Result";
    element.appendChild(resultDiv);
  }
}

Now let's remove our document.write("Hello World!"); from our index.js and let's use our class:

src/index.js

1
2
import { default as AmazingButton } from "./amazing-button";
new AmazingButton(document.getElementById("test-container"));

Now you should see a page with a button. Pressing the Button will display a random number from 0 to 9 in the box below.

Let's try our class setter and raise the maximum number to 99:

src/index.js

1
2
3
import { default as AmazingButton } from "./amazing-button";
let myClass = new AmazingButton(document.getElementById("test-container"));
myClass.maximumNumber = 99;

Now the button generate numbers from 0 to 99.

Back to top