Κλάσεις της JavaScript

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

JavaScript class is a template for JavaScript objects.

of JavaScript class

Syntax

Use the keyword class Create a class.

Always add the name 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 creating a new object.

Constructor method

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.";

Προσπαθήστε το شخصικά

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 = "Το αυτοκίνητό μου είναι " + myCar.age(year) + " χρόνια.";

Προσπαθήστε το شخصικά

Υποστήριξη προγράμματος περιήγησης

Η παρακάτω τаблицή αναφέρει την πρώτη έκδοση του προγράμματος περιήγησης που υποστηρίζει πλήρως τις κλάσεις JavaScript:

Chrome IE Firefox Safari Opera
Chrome 49 Edge 12 Firefox 45 Safari 9 Opera 36
Μάρτιος 2016 Ιούλιος 2015 Μάρτιος 2016 Οκτώβριος 2015 Μάρτιος 2016

Στη συνέχεια αυτού του οδηγού, θα μάθετε περισσότερα για τις κλάσεις του JavaScript.