Классы в JavaScript
- Предыдущая страница JS стрелочные функции
- Следующая страница JS модули
ECMAScript 2015, also known as ES6, introduced JavaScript classes.
JavaScript class is a template for JavaScript objects.
JavaScript classSyntax
Use the keyword class
Create a class.
Always add a method named constructor()
method:
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".
Классы в JavaScriptNotobject.
It is just a JavaScript object'stemplate.
Using class
If you have a class, you can use the class to create objects:
instance
let myCar1 = new Car("Ford", 2014); let myCar2 = new Car("Audi", 2019);
The above example uses Car classcreated two Car object.
The constructor method is automatically called when a new object is created.
Constructor method
Constructor is a special method:
- It must have the exact name of "constructor"
- Automatically executed when a new object is created
- 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
same as 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.";
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 = "My car is " + myCar.age(year) + " years old.";
Поддержка браузеров
В таблице ниже указаны версии браузеров, которые首个完全支持 JavaScript классы:
Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 49 | Edge 12 | Firefox 45 | Safari 9 | Opera 36 |
Март 2016 года | Июль 2015 года | Март 2016 года | Октябрь 2015 года | Март 2016 года |
В этом руководстве вы узнаете больше о классах JavaScript.
- Предыдущая страница JS стрелочные функции
- Следующая страница JS модули