簡體   English   中英

JS在多個文件上起作用。 創建課程還是使用Webpack和Babel?

[英]JS functions on multiple files. Create a class or use Webpack and Babel?

我的Javascript項目有2個JS文件(假設abc.jsdef.js )和一個html文件( index.html )。 abc.js文件中,我全局聲明了一個名為inputGraph[]的數組。 同樣在abc.js文件中,我有一個名為assignValues()的方法,該方法用於將值分配給inputGraph[]數組。 我在同一個文件getInputGraph()有另一個方法,該方法返回inputGraph數組。 在index.html文件中,我分別導入上述js文件和<script></script>標記內,分別調用assignValues()getInputGraph() (我使用getInputGraph()inputGraph數組獲取到index.html )。 我想知道我使用這些方法的方式對嗎? 由於我就像使用Object一樣使用inputGraph數組,因此我需要為其創建一個類,或者因為有更多的JS文件,所以需要將Webpack與Babel或Parcel一起使用。

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

的index.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>

我有一個全局聲明的……我使用這些方法的方式正確嗎?

不。當您說“全球”時,您就輸了。


在這種情況下,使用類來封裝graphArrayassignValue()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安裝依賴關系)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM