简体   繁体   English

从另一个JavaScript文件调用一个JavaScript函数,并在atom IDE中获取参考错误和无效状态错误以及一些警告

[英]Calling a javascript function from another javascript file and getting Reference errors and Invalid state errors and some warnings inside atom IDE

I am a new to javascript coding in p5 and i am getting errors when trying to call a function from another javascript file. 我是p5中javascript编码的新手,尝试从另一个javascript文件调用函数时遇到错误。 Here is my html file: 这是我的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>

Here is my javascript file 1: 这是我的JavaScript文件1:

function setup() {
  createCanvas(400,400);
}
function draw(){
  pr("hello world",x,y);
}

Here is my javascript file 2: 这是我的JavaScript文件2:

function pr(text,x,y){
  text(text,x,y);
}

I edited the function arguments because i forgot that text function has a different sytnax than i wrote. 我编辑了函数参数,因为我忘记了文本函数与我编写的语法不同。 Still getting errors: 仍然出现错误:

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

The files has different scope, so one isn't aware of the other. 这些文件的作用域不同,因此一个文件不知道另一个文件。 If you want a function to be accessible from another file you need to add it to a shared scope. 如果要从另一个文件访问功能,则需要将其添加到共享范围。 You can put it on the window (global scope) object and then to use it elsewhere. 您可以将其放在窗口(全局范围)对象上,然后在其他地方使用它。

file1: 文件1:

function there(text){
  console.log(text)
}

window.there = there

file2: 文件2:

function here(){
  there("hello world");
}

here()

In your html file you should first import file1 and after that file2. 在html文件中,您应该先导入file1,然后再导入file2。 That way when you call it it is already the. 这样,当您调用它时就已经可以了。

NOTE: writing on the window object is not a good practice! 注意:在窗口对象上书写不是一个好习惯! you should probably find a tool that creates a bundle an let you access a function from another file. 您可能应该找到一个创建捆绑软件的工具,让您可以从另一个文件访问功能。 Check Webpack for example. 例如,检查Webpack

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

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