抽象对象或创建类类对象

时间:2017-03-12 11:11:31

标签: javascript

很抱歉这个令人困惑的标题,我真的不知道如何命名我想做的事情。 我目前有这个代码:

const utils = (function () {

  const tabsWithAudio = {
    tabsArray: [],
    add: function (tabId) {
      const index = this.tabsArray.indexOf(tabId);
      if (index < 0) {
        this.tabsArray.push(tabId);
      }
    },
    remove: function (tabId) {
      const index = this.tabsArray.indexOf(tabId);
      if (index >= 0) {
        this.tabsArray.splice(index, 1);
      }
    },
    contains: function (tabId) {
      return (this.tabsArray.indexOf(tabId) > -1);
    },
  };


  const tabsWithWidget = {
    tabsArray: [],
    add: function (tabId) {
      const index = this.tabsArray.indexOf(tabId);
      if (index < 0) {
        this.tabsArray.push(tabId);
      }
    },
    remove: function (tabId) {
      const index = this.tabsArray.indexOf(tabId);
      if (index >= 0) {
        this.tabsArray.splice(index, 1);
      }
    },
    contains: function (tabId) {
      return (this.tabsArray.indexOf(tabId) > -1);
    },
  };

  return {
    tabsWithAudio: tabsWithAudio,
    tabsWithWidget: tabsWithWidget,
  };
}());

module.exports = utils;

然后我像这样使用它们:

const utils = require('./modules/utils');

...


utils.tabsWithAudio.add(123);

....

但是由于所有th对象都是相同的,我想创建一个类似于类的对象,我可以随时实例化,例如:

let tabsWithAudio = new utils.tabsHelper();
utils.tabsWithAudio.add(123);

我尝试了这个,但原型中的所有内容都没有导出我想:

const utils = (function () {

  const tabsHelper = function() {};
  tabsHelper.prototype = {
    tabsArray: [],
    add: function (tabId) {
      const index = this.tabsArray.indexOf(tabId);
      if (index < 0) {
        this.tabsArray.push(tabId);
      }
    },
    remove: function (tabId) {
      const index = this.tabsArray.indexOf(tabId);
      if (index >= 0) {
        this.tabsArray.splice(index, 1);
      }
    },
    contains: function (tabId) {
      return (this.tabsArray.indexOf(tabId) > -1);
    },
  };



  return {
    tabsHelper: tabsHelper,
  };
}());

module.exports = utils;

知道我错过了什么吗?这也就是什么叫做btw。

感谢你。

1 个答案:

答案 0 :(得分:0)

嘿Cornwell我读了你的问题,我的答案不会是任何'代码'。你清楚地知道你的东西,我相信你只是在寻找一些澄清。

你知道这些代码片段不是“类”是正确的。至少在经典意义上。你所指的是'模块'。更具体地说,您正在使用IIFE(创建闭包),然后返回一个对象,该对象引用了该IIFE中的函数。这是一个使用闭包的模块。

可以找到有关此模式的更多信息here。有一点需要注意。使用“类”的“框架”时模块未实例化,它们将被返回。

JavaScript类被实例化,但模式看起来不同。以下是pseudoclassical instantiation patterns.的资源。这是ES6 classes的链接,通常是语言的标题。还有一个link.关键字“new”仅与实例化相关联。实例化与类相关联。