[英]How can I include more than one Javascript file?
I want to use more Javascript files on one canvas, but I can't connect them. 我想在一个画布上使用更多Javascript文件,但无法连接它们。 For example I want to write a Javascript file that contains all functions and an other Javascript file which is using them.
例如,我要编写一个包含所有功能的Javascript文件,以及一个正在使用它们的其他Javascript文件。
Show me a guide, how can I make this connection? 向我显示指南,如何建立连接?
Thanks. 谢谢。
This is the first javascript file : 这是第一个javascript文件:
var canvas = null;
var ctx = null;
window.onload = function () {
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
line (100,100,300,300);
}
This is the secnond file: 这是第二个文件:
function line (x1,y1,x2,y2) {
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
And this is my html file: 这是我的html文件:
<!DOCTYPE html>
<html>
<head>
<title>Tutorialok</title>
<script type="text/javascript" src="CanvasElement.js"></script>
<script type="text/javascript" src="line.js"></script>
<style>
#myCanvas {
border: 1px solid #9C9898;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="600">
Sorry your browser Does not support canvas element!
</canvas>
</body>
</html>
The first file cant find the second files function. 第一个文件找不到第二个文件功能。
Use namespacing via Objects
. 通过
Objects
使用命名空间。 I don't recommend a pattern where all functions exist in one file, but this is an idea you could use. 我不建议所有文件都存在一个文件中的模式,但这是您可以使用的想法。 You MUST load file1.js before file2.js can do anything.
您必须先加载file1.js,然后file2.js才能执行任何操作。
// file1.js
window.namespace = window.namespace || {};
window.namespace.fns = {
foo: function () {}
};
// file2.js
window.namespace.fns.foo();
jsFile 1 jsFile 1
var f1 = function(){};
var f2 = function(){}
jsFile2 jsFile2
var s1 = f1();
var s2 = f2();
use this on the html page 在html页面上使用它
<script src="path/jsFile1.js"></script>
<script src="path/jsFile2.js"></script>
If you're expecting the function to hoist, I don't believe that would work between script files since each one is evaluated independently. 如果您希望函数能够提升,那么我认为这在脚本文件之间不起作用,因为每个文件都是独立评估的。 Switch the script tags around so line is in scope when CanvasElement.js loads.
切换脚本标签,以便在CanvasElement.js加载时行在范围内。
Otherwise, the global namespace is shared between the linked scripts. 否则,将在链接的脚本之间共享全局名称空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.