My second .js file has a function
function createRectangle(x, y, w, h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
ctx.fillRect(x, y, w, h);
}
But I want to call this function from my first .js file how do I do that?
My second .js file has a function
function createRectangle(x, y, w, h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
ctx.fillRect(x, y, w, h);
}
But I want to call this function from my first .js file how do I do that?
make sure your page includes second.js before first.js
an in
<script src="second.js"></script>
<script src="first.js"></script>
now within first.js you can call your createRectangle function defined in second.js
The order of includes doesn't really matter. The order of execution does. Let's say we had a javascript file:
function a() { b(); }
function b() { alert("hello!"); }
window.onload = a;
That'll work. Function a appeared before function b in the code, but what matters is the execution order. Since I didn't actually call function a nor b until window.onload, that ensures the browser has a chance to load everything before running anything.
It is a good idea to put off running JS until onload (or document.ready) because that ensures all code is loaded, including the HTML. If you try to get an element before the html dom is ready/loaded, it will fail too.
The order of inclusion of both scripts should not matter as long as the function is called in first.js after second.js is completely loaded.
PS: FYI, after DOM is parsed by the browser, the scripts included in a html page end up in a common space/scope (Hence, calling functions from other .js files is possible). In your case, defining functions like this can end up in a problem if some other .js file defines a function with the same name as yours. Your function will be overwritten in that case. A study of design patterns and structuring of code will definitely help you with such problems in future.
Add your second.js file before first.js file in one page. i.e. in other words, both should be included in the page, you are tried after the calling function.
such as,
<script src="yourpath/second.js"></script>
<script src="yourpath/first.js"></script>