[英]Calling a function from another javascript file inside a javascript file
[英]Calling a javascript function from another javascript file and getting Reference errors and Invalid state errors and some warnings inside atom IDE
我是p5中javascript编码的新手,尝试从另一个javascript文件调用函数时遇到错误。 这是我的html文件:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>p5.js example</title>
<style> body {padding: 0; margin: 0;} </style>
<script src="../p5.min.js"></script>
<script src="../addons/p5.dom.min.js"></script>
<script src="../addons/p5.sound.min.js"></script>
<script src="sketch.js"></script>
<script src="file.js"></script>
</head>
<body>
</body>
</html>
这是我的JavaScript文件1:
function setup() {
createCanvas(400,400);
}
function draw(){
pr("hello world",x,y);
}
这是我的JavaScript文件2:
function pr(text,x,y){
text(text,x,y);
}
我编辑了函数参数,因为我忘记了文本函数与我编写的语法不同。 仍然出现错误:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
Use of the orientation sensor is deprecated. p5.min.js:3:232007
Use of the motion sensor is deprecated. p5.min.js:3:232007
ReferenceError: x is not defined
这些文件的作用域不同,因此一个文件不知道另一个文件。 如果要从另一个文件访问功能,则需要将其添加到共享范围。 您可以将其放在窗口(全局范围)对象上,然后在其他地方使用它。
文件1:
function there(text){
console.log(text)
}
window.there = there
文件2:
function here(){
there("hello world");
}
here()
在html文件中,您应该先导入file1,然后再导入file2。 这样,当您调用它时就已经可以了。
注意:在窗口对象上书写不是一个好习惯! 您可能应该找到一个创建捆绑软件的工具,让您可以从另一个文件访问功能。 例如,检查Webpack 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.