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;
}
...
}
export default class MyClass {
static instance: MyClass | undefined;
static getInstance() {
if (!MyClass.instance) {
MyClass.instance = new MyClass();
}
return this.instance;
}
...
}
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();
import MyClass from './MyClass';
const myClass = MyClass.getInstance();
import MyClass from './MyClass'; const myClass = MyClass.getInstance();
or
class MyClass {
...
}
let instance;
export function getMyClassInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
class MyClass {
...
}
let instance;
export function getMyClassInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
class MyClass { ... } let instance; export function getMyClassInstance() { if (instance == null) { instance = new MyClass(); } return instance; }
import { getMyClassInstance } from './MyClass';
const myClass = getMyClassInstance();
import { getMyClassInstance } from './MyClass';
const myClass = getMyClassInstance();
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;
}
set name(newName) {
this._name = newName;
}
}
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;
}
}
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
}
class Person { constructor(name) { this._name = name; } get name() { return this._name; } }
const myName = person.name;
const myName = person.name;
const myName = person.name;
Leave a Reply