带继承的ES6 / Meteor Singleton模式

时间:2016-04-15 18:31:11

标签: javascript inheritance meteor ecmascript-6

我使用此博客编写了一个单身人士: http://amanvirk.me/singleton-classes-in-es6/

但我需要在客户端和服务器端都使用单例。

也就是说,我有三个程序:common.js

export class AppsManagerCommon {
  constructor(options) {
    // general options
    this.options = options;
    // list of registered apps
    this.apps = [];
  }
  registerApp(app) {
    a = this.apps.find(function (a) {return a.name === app.name;});
    console.log(a);
    this.apps.push(app);
  }
}

client.js

import { AppsManagerCommon } from 'common.js';
let instanceAppsManager = null;  // singleton pattern
export class AppsManager extends AppsManagerCommon {
  constructor(options) {
    if (!instanceAppsManager) {  // not yet instantiated
      super(options);
      instanceAppsManager = this;
    }
   return instanceAppsManager;
  }
}

server.js(与client.js相同)

import { AppsManagerCommon } from 'common.js';
let instanceAppsManager = null;  // singleton pattern
export class AppsManager extends AppsManagerCommon {
  constructor(options) {
    if (!instanceAppsManager) {  // not yet instantiated
      super(options);
      instanceAppsManager = this;
    }
   return instanceAppsManager;
  }
}

singletoc可以成功使用:

a = new AppsManager();
a.registerApp({name:'app1'});

但是我一旦

b = new AppsManager(); // should be the same instance

我收到错误:

ReferenceError: this hasn't been initialised - super() hasn't been called
    at BabelRuntime.possibleConstructorReturn (packages/babel-runtime.js:206:13)

我可以或多或少地理解错误的含义,但我不知道如何解决这个问题。

编辑1

注意registerApp中的存在检查不起作用,但现在不是问题

1 个答案:

答案 0 :(得分:0)

这是一个有效的解决方案:

common.js

let instanceAppsManager = null;  // singleton pattern
export class AppsManagerCommon {
  constructor(options) {
    if (!instanceAppsManager) {  // not yet instantiated
      instanceAppsManager = this;
      // general options
      this.options = options;
      // list of registered apps
      this.apps = [];
    }
    return instanceAppsManager;
  }
  registerApp(app) {
    this.apps.push(app);
  }
}

server.js(与client.js相同)

import { AppCommon, AppsManagerCommon } from 'common.js';
export class AppsManager extends AppsManagerCommon {
  constructor(options) {
      super(options);
  }
}