[英]JS functions on multiple files. Create a class or use Webpack and 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
)。 我想知道我使用這些方法的方式對嗎? 由於我就像使用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>
我有一個全局聲明的……我使用這些方法的方式正確嗎?
不。當您說“全球”時,您就輸了。
在這種情況下,使用類來封裝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=>
元素,客戶端就不需要執行很多請求。 npm
安裝依賴關系)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.