PROGRAMMING     CLIMBING

  minte9
reminder




Last update:   26-01-2022

New

Often we need to create many similar objects.
 
/**
 * Constructor:
 * 
 * The regular {...} syntax allows to create one object.
 * The 'new' operator allows us to create many similar objects.
 * 
 * Any function can be run with new, ...
 * and it will execute the shown algorithm.
 * 
 * The capital first letter is a convention ...
 * to make it clear that can be run with new.
 */

function User(name) {

    // this = {};  // implicit

    this.name = name;

    // return this; // implicit
}

let A = new User("Jack");
let B = new User("Mike");

console.log(A.name); // Jack
console.log(B.name); // Mike


/**
 * Private constructor (Singleton):
 * 
 * This encapsulate code that construct the object, ...
 * without future reuse.
 */

 let user = new function(name) {
    this.name = "John";
    this.isAdmin = true;
}

console.log(user.isAdmin); // true

Methods

We can add to this not only properties, but methods as well.
 
/**
 * We can add methods to constructor, but ...
 * 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

Questions     github Objects
Primitives
        A B C D E F
🔔
1/3