Event capturing and bubbling in Javascript
Every event is a special object used in browsers to signal that something happened to a HTML element. And JavaScript can be used to react to that …
Singleton pattern is a creational design pattern that restricts the initialization of a class (or object in general) to single instance while providing a global access point to this instance.
Usually singleton is used when we have to have only one single instance throughout the application. This can be for example:
To get always the same instance, the singleton must return its instance if already instantiated.
if (Singleton.instance instanceof Singleton) {
return Singleton.instance;
}
Singleton.instance = this;
This code should be placed in a constructor so it can return Singleton instance every time (second and any other time) the constructor is called.
Full code example
Singleton can be also implemented in functional-based javascript. But it is not used as often as in class-based JavaScript. Usually the framework you use, has its own way how to implement ‘singleton’ (i.e. useContext hook in React).
The singleton as function must be an IIFE that will return the same object all the time.
// private property hidden in scope
let instance;
// publicly accessible logic
if (!instance) {
instance = getInstance()
}
return instance;
The instance property is hidden in a scope of the IIFE and we are not able to access or modify it directly. The instance should be returned from publicly accessible method. In the code example below, the IIEF returns function getInstance() that creates instance for the first time it is accessed and always returns it. And ‘instance’ is just another function with some custom logic. In this case public method and getter of a private random number.
Full code example
Every event is a special object used in browsers to signal that something happened to a HTML element. And JavaScript can be used to react to that …
Two important tools in the TypeScript type system are type inference and type assertion. While they sound similar, they serve different purposes and …