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?


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


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);


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.


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".

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Calling a JavaScript object class that's in a separate .js file