JAVASCRIPT

  minte9
REMEMBERS




Last update:   27-01-2022

Constructor

Classes are a more advance object construct (unlike new function()).
 
/**
 * Classes
 * 
 * We already know about new function() contructor.
 * 
 * Classes are an advanced object construct.
 * It introduce great new features useful for OOP.
 * 
 * In JavaScript, a class is a kind of function.
 * Within the class, no commas are required. 
 * 
 * Classe always use strict.
 */

class User
{
    constructor (name) {
        this.name = name;
    }

    hello() {
        console.log("Hi, this is " + this.name);
    }
}
 
let a = new User("Mihai");
let b = new User("John");

a.hello(); // Hi, this is Mihai
b.hello(); // Hi, this is John

Getter

Just like literal objects, classes may include getters and setters.
 
/**
 * Get/Set
 * 
 * Such class declaration works by creating ...
 * getters and setters in Message.prototype
 */

class Message
{
    constructor (msg) {
        this.msg = msg; // invokes the setter
    }

    set msg(str) {
        str = str.toUpperCase();
        this._msg = str; // Look Here
    }

    get msg() {
        return this._msg;
    }
}
 
let obj = new Message("hello world");
console.log(obj.msg + "!"); // HELLO WORLD!

try {
    console.log(obj.msg()); // Error: msg() is not a function
} catch (err) {}

Questions     github Classes
Binding
        A B C D E F
🔔
1/2