javascript - 多个文件上的 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>
解决方案
我有一个全局声明......是我使用这些方法的方式对吗?
不,你说“全球”的那一刻你就输了。
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
)
推荐阅读
- ios - 在 Swift 的 UIPageViewController 中,视图不显示“setViewController”
- c++ - 想找到该领域得分最高的最佳路径
- javascript - 如何检查深度嵌套的道具
- mysql - 视图页面中的codeigniter Json表未加载表
- swift - Xcode:一旦给定自定义类名,子视图控制器就无法正确加载
- c# - 使用 MultiDataTrigger 绑定两个用户控件
- c# - 限制 .NET MVC 应用程序上的登录用户数
- unit-testing - 如果我已经在 Vue.js 应用程序中使用 Cypress,是否需要一个单元测试框架?
- html - 如何从它的父元素的中心缩放标签?
- .htaccess - 我希望仅使用 .htaccess 文件为我的 URL 重写 URL