首页 > 解决方案 > 多个文件上的 JS 函数。创建一个类还是使用 Webpack 和 Babel?

问题描述

我的 Javascript 项目有 2 个 JS 文件(假设abc.js, def.js)和一个 html 文件(index.html)。在abc.js文件中,我全局声明了一个名为inputGraph[]. 同样在abc.js文件中,我有一个名为的方法assignValues(),用于将值分配给inputGraph[]数组。我在同一个文件中有另一个方法,getInputGraph()它返回 inputGraph 数组。在 index.html 文件中,我分别导入上面的 js 文件和<script></script>我调用的标签assignValues()getInputGraph()(我getInputGraph()用来获取inputGraph数组的index.html)。我想知道我使用这些方法的方式是否正确?由于我inputGraph像对象一样使用数组,我需要为它创建一个类,还是需要将 Webpack 与 Babel 或 Parcel 一起使用,因为有更多的 JS 文件。

abc.js

 var inputGraph=[];

    function assignValues(){
       for(let i=0; i<5; i++){
          inputGraph.push(i);
       }
    }

function getInputGraph(){
   return this.inputGraph;
}

def.js

//some ither functions

索引.html

<!DOCTYPE html>
   <head>
      <script src="./abc.js"></script>
      <script src="./def.js"></script>
   </head>
   <body>
      <script>
         var graphArray = [];
         assignValues();
         graphArray = getInputGraph();
         console.log(graphArray );
      </script>
   </body>
</html>

标签: javascriptarraysclasswebpackbabeljs

解决方案


我有一个全局声明......是我使用这些方法的方式对吗?

不,你说“全球”的那一刻你就输了。


graphArray在这种情况下,使用一个类来封装你的,assignValue()getInputGraph()属性确实是有意义的

这种效果的东西:

class Graph {
  constructor() {
    this.graphArray = [];
  }

  assignValues() {
    // do something to this.graphArray
    // for example:
    this.graphArray.push({x: 42, y: 57});
  }

  getInputGraph() {
    // return a new graph array
    return [{x: 43, y: 58}];
  }
}

// usage
const graph = new Graph();
graph.graphArray = graph.getInputGraph();
graph.assignValues();
console.log(graph.graphArray); // [{x: 43, y:58}, {x: 42, y: 57}];

您并不一定需要使用 webpack 或 Babel,但它们为您提供了一些在生产项目中通常难以忽视的优势:

  • 你得到一个捆绑文件而不是几个文件,所以你只需要一个<script src=>元素,客户端不需要执行很多请求。
  • 你会得到一个文件,即使在不支持类的浏览器(即 IE11)中也能工作
  • 你得到缩小
  • 您可以解决依赖项(您可以使用 安装依赖项npm

推荐阅读