Calling a JavaScript object class contained in a separate .js file

I created a JavaScript string constructor, and I use it with many different .js files in my project.

Is it possible to create this class in a separate .js file and call it from all other scripts that initialize it, like a C # class file?

Is this possible, or am I continuing to copy and paste it at the bottom of each .js file that uses it?

+2
source share
4 answers

Yes, that should not be a problem. Just include the .js files in the correct order on your html pages.

+5
source

If you include the file on your main HTML page along with other js, you can use the "class" however you want:

<script src="js1.js" type="text/javascript"></script> <script src="js2.js" type="text/javascript"></script> 

In the above example, you can now instantiate a new instance of the object from js1.js with the code in js2.js. To do this with pure javascript, you need to add a script tag in the DOM or use AJAX to extract the script file and eval() it.

 // Create a <script> element var scriptEl = document.createElement("script"); scriptEl.src = "js2.js"; scriptEl.type = "text/javascript"; // Append it to the <head> document.getElementsByTagName("head")[0].appendChild(scriptEl); 
+3
source

To be absolutely correct, this is not the order of inclusion that matters, but the order of code execution. In most cases, Andy and Segfault's instructions are great, but sometimes they include a class file before its consumers are scarce. For example, if you use ExtJS and you accidentally define your class inside the onReady handler as follows:

 Ext.onReady(function() { myClass = ... }.bind(this)); 

it will not be executed by the time your second src file is included in the page and is executed.

I know the example is a little far-fetched :), but just make sure your code is executed in the correct order, and not just in the correct order.

+1
source

I came across this question and I wanted to add something (which probably was not there a few years ago).

I even thought that you can add each script to your "index.html", this is not a very nice practice (imho). Especially if you think you can write an extension (~ framework). You do not want to annoy the user with a bunch of script tags that he must add to your code. What you need is one line:

 <script src="yourFramework" (...) /> 

However, using RequireJS , you can do this. You have the freedom to separate your code, but "your user" still does not need to add a novel to the "script" section.

0
source

Source: https://habr.com/ru/post/911719/


All Articles