JS singleton design pattern

 First, the concept:

  • A class

  • Only one instance of

  • Provide a global access point to access it

 Second, to achieve:

class SimpleOne {     
    constructor (name) {         
        this.name = name;     
    }     
    getName (propsName) { 
        this.name = propsName;         
        return typeof this.name;     
    } 
}

const a = new SimpleOne('a').getName();
const b = new SimpleOne('b').getName();

a === b // true

 Three, JavaScript singleton

    In our development, many students may not know a single case in the end what is, how to use a single case, but the code they wrote, but just to meet the requirements of Singleton pattern.

    To achieve a login pop, no matter what page or pages in that place, click the Login button, login window will pop up. Some students will write a global target to achieve the landing window function, yes, this can indeed achieve the desired effect of landing, but also meet the requirements of singletons, but this implementation is actually a coincidence, or a beautiful mistake .

    As the global object, or exactly in line with global variables can be globally accessible singleton, and is unique. But we all know that global variables can be covered, especially for junior developers, regardless of beginning to define what are basically global, such benefits are easy to access, the downside is that without a watchful eye will cause the conflict, especially when doing a large project team, so mature and experienced developers minimize the overall statement, and in the development of our global variables to avoid contamination of the usual practice is as follows:

  • Global namespace
  • Using closures

Guess you like

Origin www.cnblogs.com/JockerM/p/12063563.html