PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Constructor

In the modern JavaScript, there is a more advanced class construct. Within the class, no commas are required.
 
class User
{
    constructor (name) {
        this.name = name;
    }

    sayHi() {
        console.log("Hi, this is " + this.name + "!");
    }
}

let user = new User("John");

user.sayHi(); // Hi, this is John!
... 6 lines
 

Class type

In JavaScript, a class is a kind of function. Sometimes people say that class is a syntactic sugar.

Differences

There are important differences between classes and functions. All code inside the class construct is automatically in strict mode.
 
class User
{
  constructor(name) { 
      this.name = name; 
  }
}

console.log(typeof User); // function (class is a function)

console.log(User === User.prototype.constructor); // true (class)
... 3 lines
 
Getters And Setters    (2/4)

Getters and Setters

Just like literal objects, classes may include getters/setters.
 
class User
{
    constructor (name) {
        this.name = name;
    }

    set name(value) {
        this._name = value; // Look Here
    }

    get name() {
        return this._name;
    }
}

let user = new User("John");

console.log(user.name); // John

console.log(user.name()); // Error: name is not a function
... 10 lines
 
Losing This Problem    (3/4)

Losing This Problem

Context

An object method could be passed around and called in another context. This won’t be a reference to its object any more.
 
class Button
{
    constructor(value)
    {
        this.value = value;
    }

    click()
    {
        console.log(this.value);
    }
}

let button = new Button("hello");

setTimeout(button.click, 1000); // undefined
... 8 lines
 
Bind To Object    (4/4)

Bind to object

You can bind the method to object.
 
class Button
{
    constructor(value)
    {
        this.value = value;
        this.click = this.click.bind(this); 
    }

    click()
    {
        alert(this.value);
    }
}

let button = new Button("hello");

setTimeout(button.click, 1000); // hello
... 9 lines
 

Elegant syntax

Class fields provide a more elegant syntax for the latter solution.
 
class Button
{
    constructor(value)
    {
        this.value = value;
    }

    click = () =>
    {
        console.log(this.value);
    }
}

let button = new Button("Hello World");

setTimeout(button.click, 1000); // Hello World
... 8 lines
 

Questions    
Inheritance

        A B C D E F
🔔
1/5