简体   繁体   English

将Javascript文件导入另一个Javascript文件

[英]Import a Javascript file into another Javascript file

I'm creating a simple HTML5 JS game, and at the moment my javascript file has reached nearly 1500 lines and it is slowly getting harder and harder to manage with so much more to do, is there a simple way to split some of the script up into "classes" which I mean separate files and then import all the "classes" files into one "main" file? 我正在创建一个简单的HTML5 JS游戏,目前我的javascript文件已达到近1500行,并且正在逐渐变得越来越难以管理更多的事情,是否有一种简单的方法来分割一些脚本到“类”,我的意思是单独的文件,然后将所有“类”文件导入一个“主”文件?

So for example I have this 所以例如我有这个

File1.js File1.js

function pointInRect(pnt_x, pnt_y, rect_x, rect_y, rect_w, rect_h)
{
if ( (pnt_x >= rect_x) && (pnt_x <= rect_x + rect_w - 1) )
{
    if ( (pnt_y >= rect_y) && (pnt_y <= rect_y + rect_h - 1) )
    {return true;}
}
return false;
}

File2.js File2.js

if( pointInRect(1,1,1,1,1,1) == true){ console.log("Yo, there be a collision");}

how do I get file2 import file1 and use that method? 如何获取file2 import file1并使用该方法? If anyone could help me that would be awesome, it would really help me with manage my huge JS file. 如果有人能帮助我这将是非常棒的,它将真正帮助我管理我的巨大的JS文件。

Canvas 帆布

Just add the files with the script tag in the html, they will be executed in order. 只需在html中添加带脚本标记的文件,它们就会按顺序执行。

<script type="text/javascript" src="file1.js">
<script type="text/javascript" src="file2.js">

Others have pointed out how you break code in to multiple files. 其他人已经指出了如何将代码分解为多个文件。 If you want to organize your code within those files, use scoped variables rather than global, and are familiar with classes/objects, then you might try something like this: 如果您想在这些文件中组织代码,使用范围变量而不是全局,并且熟悉类/对象,那么您可以尝试这样的事情:


//class1.js
MYNS = MYNS | {};
MYNS.Class1 = {};
MYNS.Class1.prototype.pointInRect = function(){
  //magic here
};

//class2.js
MYNS = MYNS | {};
MYNS.Class2 = {};
MYNS.Class2.prototype.anotherMethod = function(){
  //more magic
};

//main.html
<script type="text/javascript" src="class1.js">
<script type="text/javascript" src="class2.js">

var class1 = new MyNS.Class1();
var class2 = new MyNS.Class2();

class1.pointInRect ();
class2.anotherMethod ();

But keep in mind that JavaScript is not OO in the traditional sense, and these are not true classes. 但请记住,JavaScript不是传统意义上的OO,而且这些不是真正的类。 Rather, this is a way of organizing JS code in to something that resembles classes and objects. 相反,这是一种将JS代码组织成类似于类和对象的方法。 If you try to do things resembling inheritance, etc., then the required complexity and level of understanding goes up very quickly. 如果你尝试做类似于继承等的事情,那么所需的复杂性和理解水平会很快上升。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM