Javascript – Algorithm (4)

How to create a singleton class/ object?

export default class MyClass {

    static instance: MyClass | undefined;

    static getInstance() {
        if (!MyClass.instance) {
            MyClass.instance = new MyClass();
        }

        return this.instance;
    }

    ...
}
import MyClass from './MyClass';

const myClass = MyClass.getInstance();

or

class MyClass {
    ...
}

let instance;
export function getMyClassInstance() {
    if (instance == null) {
        instance = new MyClass();
    }

    return instance;
}
import { getMyClassInstance } from './MyClass';

const myClass = getMyClassInstance();

How to use getter/ setter in class?

class Person {
    constructor(name) {
        this._name = name;
    }

    get name() {
        return this._name;
    }

    set name(newName) {
        this._name = newName;
    }
}
class Person {
    constructor(name) {
        this._name = name;
    }
    get name() {
        return this._name;
    }
}
const myName = person.name;

Be the first to comment

Leave a Reply

Your email address will not be published.


*