34523

Calling a JavaScript object class that's in a separate .js file

I have created a string builder JavaScript object and I'm using it with many different .js files in my project.

Can I create this class in a separate .js file and call it from all the other scripts that instansiate it, just like a C# class file?

Is this possible, or do I continue copying and pasting it into the bottom of every .js file that uses it?

Answer1:

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

Answer2:

If you include the file in your main HTML page with your other js, you can then use the "class" as you wish:

<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 an object from js1.js with the code in js2.js. To do this with pure javascript, you would have to add the script tag to the DOM, or use AJAX to fetch 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);

Answer3:

To be perfectly correct, it's not the order of inclusion that matter, but rather the order of executing code. In most cases, Andy's and Segfault's instructions are just fine, but sometimes including the class file before its consumers isn't sufficient. For example, if you use ExtJS and you happen to define your class inside an onReady handler like this:

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

then it won't get executed by the time your second src file is included into the page and executed.

I know, the example is a bit far-fetched :) but just make sure that your code is executed in the right order, not just included in the right order.

Answer4:

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

Even thought you can add every single script to your "index.html" it's not a very beautiful practice (imho). Especially if you consider that you may want to write a extension (~ framework). You don't want to annoy the user with a bunch of script tags he has to add to his code. What you want is a single line like this:

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

However, with the use of RequireJS you are able to achieve this. You've the freedom to separate your code and "your user" still don't have to add a novel to his "script section".

Recommend

  • can more than one function be added in an external javascript file? i.e .js file? [closed]
  • Calling a function from one JavaScript file which requires another
  • MapBox - Cluster Zooming
  • JPS useBean with HashMap
  • Cannot instantiate the type Image java?
  • How to initialize context? [closed]
  • Adding a model to a Marionette CollectionView's collection doesn't trigger onItemAdd callb
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Highlight one bar in a series in highcharts?
  • HTML download movie download link
  • Apache 2.4 and php-fpm does not trigger apache http basic auth for php pages
  • How to add date and time under each post in guestbook in google app engine
  • Updating server-side rendering client-side
  • Fill an image in a square container while keeping aspect ratio
  • MySQL WHERE-condition in procedure ignored
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Symfony2: How to get request parameter
  • Display Images one by one with next and previous functionality
  • Weird JavaScript statement, what does it mean?
  • jquery mobile loadPage not working
  • Web-crawler for facebook in python
  • Calling of Constructors in a Java
  • PHP: When would you need the self:: keyword?
  • How to get icons for entities from eclipse?
  • A cron job substitute?
  • trying to dynamically update Highchart column chart but series undefined
  • Proper way to use connect-multiparty with express.js?
  • Load html files in TinyMce
  • How to set the response of a form post action to a iframe source?
  • Setting background image for body element in xhtml (for different monitors and resolutions)
  • How to get Windows thread pool to call class member function?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • JaxB to read class hierarchy
  • costura.fody for a dll that references another dll
  • Binding checkboxes to object values in AngularJs
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal