简体   繁体   中英

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. Here is my html file:

<!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:

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

Here is my javascript file 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:

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

window.there = there

file2:

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

here()

In your html file you should first import file1 and after that 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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