CLASS DEFINITION
In object-oriented programming, a class is a construct of a programming language used as a model for creating objects. The model includes attributes and methods that will be shared by all objects created (instances) from the class. An “object” is, in fact, the instance of a class. In modern JavaScript there is a more advanced “class” construct, which introduces very useful new possibilities for object-oriented programming.
THE SYNTAX OF CLASS
class MyClass {
// metodi della classe
constructor() { … }
method1() { … }
method2() { … }
method3() { … }
…
}
new MyClass() will create a new object with all methods in the class. The constructor() method is called automatically by new, so we can use it to initialize the object.
For example:
class User {
constructor(name) {
this.name = name;
}
sayHi() {
alert(this.name);
}
}
// Utilizzo:
let user = new User(“John”);
user.sayHi();
When called new User(“John”):
- A new object is created;
- The constructor () method is called and assigns the given argument to this.name.… Now we can call the methods, for example user.sayHi.
WHAT IS A CLASS
So, what exactly is a class? Contrary to what one might think, this is not a completely new concept. So let’s see what a class actually is. This will help us understand more complex aspects. In JavaScript, a class is a kind of function.
Observe:
class User {
constructor(name) { this.name = name; }
sayHi() { alert(this.name); }
}
// prova: User è una funzione
alert(typeof User); // function
The construct class User {…} therefore:
- Create a function called User, which becomes the result of the class declaration. The instructions of the function come from the constructor method (considered empty if not present);
- Save all methods (like sayHi) inside User.prototype.
When we call a method from an object, it will be taken from the prototype. Thus, a new User object has access to the methods of the class.
We can represent the result of the User class declaration as:
The following code will allow you to analyze it:
class User {
constructor(name) { this.name = name; }
sayHi() { alert(this.name); }
}
// una classe è una funzione
alert(typeof User); // function
// …o, più precisamente, il costruttore
alert(User === User.prototype.constructor); // true
// I metodi sono in User.prototype:
alert(User.prototype.sayHi); // il codice del metodo sayHi
// ci sono due funzioni all’interno del prototipo
alert(Object.getOwnPropertyNames(User.prototype)); // constructor, sayHi
// la classe User usando solo funzioni
// 1. Costruttore
function User(name) {
this.name = name;
}
// tutte le funzioni hanno un costruttore predefinito (di default)
// dunque non va creato
// 2. Aggiungiamo un metodo al prototipo
User.prototype.sayHi = function() {
alert(this.name);
};
// Utilizzo:
let user = new User(“John”);
user.sayHi();
The result of this code is about the same. It is therefore logical to think that class is only a syntax sugar. There are, however, some important differences. A function created through class is labeled with the special internal property [[IsClassConstructor]]: true. So it’s not exactly the same as creating it manually. Unlike a normal function, the constructor of a class can only be called via the new keyword:
class User {
constructor() {}
}
alert(typeof User); // funzione
User(); // Errore: Il costruttore della classe può essere richiamato solo attraverso ‘new’
Also, in most JavaScript engines the constructor starts with “class”
class User {
constructor() {}
}
alert(User); // class User { … }
- There are other differences, which we will discover later.
- Methods of classes are uncountable. The definition of a class sets the enumerable flag to false for all methods within the “prototype”.
This is good, as we don’t want to display methods when we use a for..in loop to display an object.
3. The contents of a class always run in strict.
In addition to these, the class syntax brings other features, which we will explore later.
THE CLASS EXPRESSION
Like functions, classes can be defined within another expression, passed as a parameter, returned, assigned, etc.
Here is a small example:
let User = class {
sayHi() {
alert(“Hello”);
}
};
Similar to Named Function Expression, classes may or may not have a name. If a class has a name, it is visible only within the class:
// “Named Class Expression”
let User = class MyClass {
sayHi() {
alert(MyClass); // MyClass è visibile solo all’interno della classe
}
};
new User().sayHi(); // funziona, restituisce la definizione di MyClass
alert(MyClass); // errore, MyClass non è visibile al di fuori della classe
GETTER AND SETTER
As with literal objects, classes can include getters/ setters, generators, properties, etc.
The following example implements user.name through get/set:
class User {
constructor(name) {
// invoca il setter
this.name = name;
}
get name() {
return this._name;
}
set name(value) {
if (value.length < 4) {
alert(“Name is too short.”);
return;
}
this._name = value;
}
}
let user = new User(“John”);
alert(user.name); // John
user = new User(“”); // Nome troppo corto.
In the examples above, the User class contained only methods. Let’s add a property:
class User {
name = “Mario Rossi”;
sayHi() {
alert(`Hello, ${this.name}!`);
}
}
new User().sayHi();
So we just write “=” in the declaration. The important difference of the fields of a class is that they are set on the individual object and not on User.prototype:
class User {
name = “John”;
}
let user = new User();
alert(user.name); // John
alert(User.prototype.name); // undefined