New
Often we need to create many similar objects.
/**
* The 'new' operator allows to create many similar objects
* The regular {...} allows to create only one object
*
* Any function can be run with new
* The capital first letter is a convention
*
* Private constructor (Singleton):
* Encapsulate code that construct the object,
* without future reuse
*/
function User(name) {
this.name = name;
// this = {}; // implicit
// return this; // implicit
}
let A = new User("Jack");
let B = new User("Mike");
let C = new function(name) { // Singleton
this.name = "John";
this.isAdmin = true;
}
console.log(A.name); // Jack
console.log(B.name); // Mike
console.log(C.isAdmin); // true
Methods
We can add to this not only properties, but methods as well.
/**
* We can add methods to constructor
* For more complex syntax, we will use classes
*
* JavaScript provides constructor functions for many
* built-in language objects: like Date or Set
*/
function User(name, birthdate) {
this.name = name;
this.age = new Date().getFullYear() - new Date(birthdate).getFullYear();
this.isAdult = this.age >= 18;
this.show = () => {
console.log(this.name + ' is adult: ' + this.isAdult);
}
}
let user = new User("John", '01-01-1980');
user.show(); // John is adult: true
Last update: 432 days ago