【ES6】使用Proxy实现单例模式

前言

由于JS没有private关键字,无法私有化构造器,所以下面代码无法限制:

javascript 复制代码
class Person {
  constructor() {
    console.log("Person created");
  }
}

const p1 = new Person();
const p2 = new Person();

console.log(p1 === p2); // false

实现

通过 Person.getInstance() 生成对象

javascript 复制代码
class Person {
  constructor() {
    console.log("Person created");
  }
  static _ins = null
  static getInstance() {
    if (!this._ins) {
      this._ins = new Person();
    }
    return this._ins;
  }
}

const p1 = Person.getInstance();
const p2 = Person.getInstance();

console.log(p1 === p2);

但是如果创建对象时使用new Person(),仍无法实现单例模式。

下面封装一个函数,把任何类传入,将其变为单例模式:

javascript 复制代码
function singleton(className) {
  let ins
  return class {
    constructor(...args) {
      if (!ins) {
        ins = new className(...args)
      }
      return ins
    }
  }
}
class Person {
  constructor() {
    console.log("Person created");
  }
}

// const p1 = new Person();
// const p2 = new Person();
const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();

console.log(p1 === p2);

但是这种实现方式仍有缺陷,并不能添加原型方法

javascript 复制代码
const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();
SingletonPerson.prototype.say = function () {
  console.log("hello world");
}
p1.say();

下面使用 Proxy 实现,不返回一个新类,而是代理,给代理对象的原型上加方法等于直接给该对象的原型加方法。

javascript 复制代码
function singleton(className) {
  let ins
  return new Proxy(className, {
    construct(target, args) {
      if (!ins) {
        ins = new target(...args);
      }
      return ins
    }
  })
}
class Person {
  constructor() {
    console.log("Person created");
  }
}
const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();
SingletonPerson.prototype.say = function () {
  console.log("hello world");
}
p1.say();
console.log(p1 === p2);
相关推荐
TAEHENGV16 小时前
导入导出模块 Cordova 与 OpenHarmony 混合开发实战
android·javascript·数据库
GISer_Jing16 小时前
交互式圣诞树粒子效果:手势控制+图片上传
前端·javascript
放逐者-保持本心,方可放逐16 小时前
PDFObject 在 Vue 项目中的应用实例详解
前端·javascript·vue.js
捻tua馔...17 小时前
mobx相关使用及源码实现
开发语言·前端·javascript
cypking17 小时前
解决 TypeScript 找不到静态资源模块及类型声明问题
前端·javascript·typescript
澄江静如练_17 小时前
侦听器即watch
前端·javascript·vue.js
console.log('npc')18 小时前
vue3文件上传弹窗,图片pdf,word,结合预览kkview
前端·javascript·vue.js·pdf·word
BD_Marathon18 小时前
Router_路由传参
前端·javascript·vue.js
Dreamcatcher_AC18 小时前
前端面试高频13问
前端·javascript·vue.js
AI陪跑18 小时前
深入剖析:GrapesJS 中 addStyle() 导致拖放失效的问题
前端·javascript·react.js