记录JS创建单例模式

128 阅读1分钟

ES5

function Person() {
  if (!Person._instance) {
    // constructor
    this.name = "姓名";
    Person._instance = this;
  }
  return Person._instance;
}

const p1 = new Person();
const p2 = new Person();
console.log(p1 === p2); // true

ES6

class Person {
  constructor() {
    if (!Person._instance) {
      // constructor
      this.name = "姓名";
      Person._instance = this;
    }
    return Person._instance;
  }
}

const p1 = new Person();
const p2 = new Person();
console.log(p1 === p2); // true

单例模式的高阶函数

function Person() {
  this.name = "姓名";
}

function SingleWrapper<T>(Constructor: T): T {
  // 排除非函数与箭头函数
  if (!(Constructor instanceof Function) || !Constructor.prototype) {
    throw new Error("不是合法的构造函数");
  }
  let instance;
  return function (...args) {
    if (!instance) {
      instance = new Constructor(...args);
    }
    return instance;
  };
}

const SinglePerson = SingleWrapper(Person);
const p1 = SinglePerson();
const p2 = SinglePerson();
console.log(p1 === p2); // true