Simplest/Cleanest way to implement singleton in JavaScript?

后端 未结 30 1397
名媛妹妹
名媛妹妹 2020-11-22 05:17

What is the simplest/cleanest way to implement singleton pattern in JavaScript?

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 05:22

    In ES6 the right way to do this is:

    class MyClass {
      constructor() {
        if (MyClass._instance) {
          throw new Error("Singleton classes can't be instantiated more than once.")
        }
        MyClass._instance = this;
    
        // ... your rest of the constructor code goes after this
      }
    }
    
    var instanceOne = new MyClass() // Executes succesfully 
    var instanceTwo = new MyClass() // Throws error

    Or, if you don't want an error to be thrown on second instance creation, you can just return the last instance, like so:

    class MyClass {
      constructor() {
        if (MyClass._instance) {
          return MyClass._instance
        }
        MyClass._instance = this;
    
        // ... your rest of the constructor code goes after this
      }
    }
    
    var instanceOne = new MyClass()
    var instanceTwo = new MyClass()
    
    console.log(instanceOne === instanceTwo) // logs "true"

提交回复
热议问题