Javascript: calling a function from another file

I am just a new Javascript fan, so when I read the Javascript document, there are a lot of complex structures that I cannot execute.

Here is a brief description of the Javascript code I'm reading: in my case, there are two main files: Helper.js and Circle.js .

There is a method name in Helper.js: using:function(param1,param2) . Below is the code for Circle.js :

 Helper.using('py.Figures', function (ns) { ns.Circle = function (params) { // some additional methods and code here } ns.Alert = function(){ // for the test purpose alert('hello'); } }); 

And in the test.html file, I write code like this:

 <script src="Helper.js"></script> <script src="circle.js"></script> <script> test = function(){ py.Figures.Alert(); // calling for testing purpose } </script> <body onload="test();"></body> 

When I launch Chrome and view the console, I encounter this error:

Uncaught TypeError: Object # does not have a 'Alert' method

This means that I have not imported this class yet. Tell me how to call a function from another file. In my case, this is: Alert() call

Thanks:)

@ Edit: I added some links for the code:

Helper.js

Circle.js

+7
source share
2 answers

Why don't you take a look at this answer

Including javascript files inside javascript files

In short, you can upload a script file using AJAX or put a script tag in the HTML to include it (before a script that uses the functions of another script). The link I posted is a great answer and contains some examples and explanations of both methods.

+7
source

Yes, you can. Just check out my fiddle for clarification. For demonstration purposes, I saved the code in the violin in the same place. You can extract this code as shown in two different Javascript files and load them into an html file.

https://jsfiddle.net/mvora/mrLmkxmo/

  /******** PUT THIS CODE IN ONE JS FILE *******/ var secondFileFuntion = function(){ this.name = 'XYZ'; } secondFileFuntion.prototype.getSurname = function(){ return 'ABC'; } var secondFileObject = new secondFileFuntion(); /******** Till Here *******/ /******** PUT THIS CODE IN SECOND JS FILE *******/ function firstFileFunction(){ var name = secondFileObject.name; var surname = secondFileObject.getSurname() alert(name); alert(surname ); } firstFileFunction(); 

If you create an object using the constructor function and try to access this property or method in the second file, it will give you access to properties that are present in another file.

Just take care of the sequence of including these files in index.html

+1
source

All Articles