Klasy w JavaScript

ECMAScript 2015, also known as ES6, introduced JavaScript classes.

JavaScript class is a template for JavaScript objects.

JavaScript class

Syntax

Use the keyword class Create a class.

Always add a method named constructor() methods:

Syntax

class ClassName {
  constructor() { ... }
}

instance

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}

The above example creates a class named "Car".

The class has two initial properties: "name" and "year".

Klasy w JavaScriptNotobject.

It is just a JavaScript object'sTemplate.

Using a class

If you have a class, you can use it to create objects:

instance

let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);

Spróbuj sam

The above example uses Car classTwo were created Car object.

The constructor method is automatically called when creating a new object.

Constructor method

The constructor method is a special method:

  • It must have the exact name of "constructor"
  • Automatically executed when creating a new object
  • Used to initialize object properties
  • If the constructor method is not defined, JavaScript will add an empty constructor method.

Class methods

Creating class methods

Syntax

like object methods.

Use the keyword class Create a class.

Always add constructor() methods.

Then add any number of methods.

Syntax

class ClassName {
  constructor() { ... }
  method_1() { ... }
  method_2() { ... }
  method_3() { ... }
}

Create a class method named "age" that returns the age of the car:

instance

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age() {
    let date = new Date();
    return date.getFullYear() - this.year;
  }
}
let myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML = "My car is " + myCar.age() + " years old.";

Spróbuj sam

You can send parameters to class methods:

instance

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age(x) {
    return x - this.year;
  }
}
let date = new Date();
let year = date.getFullYear();
let myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML = "Mój samochód ma " + myCar.age(year) + " lat.";

Spróbuj sam

Obsługa przeglądarek

Poniższa tabela podaje pierwszą wersję przeglądarki, która w pełni obsługuje klasy JavaScript:

Chrome IE Firefox Safari Opera
Chrome 49 Edge 12 Firefox 45 Safari 9 Opera 36
Marzec 2016 roku Lipiec 2015 roku Marzec 2016 roku Październik 2015 roku Marzec 2016 roku

W dalszej części tego kursu dowiesz się więcej o klasach JavaScript.