将类转换为函数

问题描述 投票:0回答:1

我正在制作一个实时应用程序,想将此class代码转换为function

下面的功能等效吗?从任何人都可以看到,将其保留为类而不是函数会有好处吗?

class IdeaService {
  constructor() {
    this.ideas = [];
  }

  async find() {
    return this.ideas;
  }

  async create(data) {
    const idea = {
      id: this.ideas.length,
      text: data.text,
      tech: data.tech,
      viewer: data.viewer
    };

    idea.time = moment().format('h:mm:ss a');

    this.ideas.push(idea);

    return idea;
  }
}

功能

function ideaService() {

let ideas = [];

 async find() {

  return ideas;

 }

 async create(data) {

 const idea = {

      id:     ideas.length,
      text:   data.text,
      tech:   data.tech,
      viewer: data.viewer

    }

    idea.time = moment().formate('h:mm:ss a');

    ideas.push(idea);

    return idea;

 }

}
javascript class momentjs feathersjs
1个回答
0
投票

尝试一下

let IdeaService = (function() {
    let ideas = [];

    async function find() {
        return ideas;
    }

    async function create(data) {
        const idea = {
            id: ideas.length,
            text: data.text,
            tech: data.tech,
            viewer: data.viewer
        };

        idea.time = moment().format('h:mm:ss a');
        ideas.push(idea);
        return idea;
    }

    return {
        find,
        create
    }
})();

编辑!如果您希望此模块在运行此文件时不被实例化,请删除();。在末尾。因此功能为:

IdeaService = (function() {
});

并实例化为:

let ideaService = IdeaService();
© www.soinside.com 2019 - 2024. All rights reserved.