4

I am new to javaScript and am unsure how to go about creating a new js library and referencing this in another js file.

If I have a standalone file Utilities.js

var Utilities= 
{
   show: function(input)
   {
      alert(input);
   }
};

Am I missing something as to how a library should be defined standalone?

My second question is how to use that is sub-sequent js files. What I did so far is:

<script type="text/javascript" src="resources/Utilities.js"></script>

In my index.html. Is this enough to reference it as:

Utilities.show("Hello");

In any other java script file?

I tested it in this fashion and got and error "Utilities is not defined"

NOTE: This is just an example and not my full and practical purpose.

10
  • 1
    Might I suggest following a pattern where users of your library can bundle things with Browserify? browserify.org Commented Jun 23, 2015 at 21:14
  • 1
    That does not answer either of my questions. Commented Jun 23, 2015 at 21:16
  • 2
    So far that looks fine to me. I don't think this question is adequately scoped here though. Commented Jun 23, 2015 at 21:17
  • So if that first part of code is the only thing in my Utilities.js file then it can be properly referenced? Also is Utilities.show("X"); how I would use it? Commented Jun 23, 2015 at 21:19
  • @MatthewSegreti Actually, it does. But I posted it as a comment in any case. Commented Jun 23, 2015 at 21:21

5 Answers 5

6

Yes, including that Javascript file with that global variable declared is enough to call your methods this way Utilities.show("Hello"); from another Javascript file loaded after Utilities.js or inside a <script></script> section of your html.

But you can actually improve it a little, following the module pattern and exposing only the functions you really need to the global scope (you'll likely write some functions that the users of your library should not call directly, this allows you to do it in a clean way):

var Utilities=Utilities||(function () {

   //Accessible only here
   var privateArray=[];

   //Cannot be called from outside this function
   var privateFunction=function(){
   }

   //Return only what must be publicly accessible, in this
   //case only the show() method
   return {
      show: function(input){
         privateFunction();
         alert(input);
      }
   }
})();

That (function () { /* Code */})();, defining a new scope for your code will also avoid name clashes with other global javascript object/functions.

Sign up to request clarification or add additional context in comments.

7 Comments

So why do I get "Utilities is not defined" in my main.js?
All the advice regarding modules is worth heeding. But this is the best, most direct answer so far. It answers the question and suggests a relatively simple improvement (the var Utilities = Utilities || is key here as it allows you to load the script multiple times from various places without overwriting your global Utilities object in the browser's memory)
@MatthewSegreti is your main.js loaded after Utilities.js? I loaded and tested your script like this in an HTML file, and it worked fine: <script type="text/javascript" src="/tmp/Utilities.js"></script> <script>Utilities.show("Hello");</script>
It is. I still get "Utilities is not defined" when I run.
Verify that Utilities.js is really in resources/ doing a view source on your page and clicking that js. If you load the js file before calling Utilities.show and the file is really loaded it must work. If you plan to call it inside a <script> in the page body try loading it inside <head>.
|
5
  1. It is OK to use object literals, but you can define libraries using other patterns (module, revealing module, constructors, etc).

I recommend these links to understand primitives, scopes, closures, object literals, etc.

http://bonsaiden.github.io/JavaScript-Garden/

http://jsbooks.revolunet.com/

  1. To call the method inside index.html you need to add a tag.

    <script> Utilities.show("Hello"); </script>

But this approach it's not recommended. Instead of it, you can create a new JS file to run your library code.

<script type="text/javascript" src="resources/Utilities.js"></script> <script type="text/javascript" src="resources/main.js"></script>

In main.js

Utilities.show("Hello");

Hope it helps.

Comments

1

Given the fact that you gave, within yout question, zero context of what you're trying to achieve, the best answer to your original question is that it depends.

If you just need a bunch of files and you're done (like in your example, Utilities.js and a few more) then you're ok with the way you're heading to.

But of course, you'll allways want to scale your front end and thus you should adhere to some architectural pattern. So, if you're building a client side (browser-side) application, then you should really implement your libraries using the module pattern, and begin your project from a good project example / scaffold.

On the other hand, if you're rendering the html on server (e.g. you're using PHP to render the final html file that will be sent to browser) and you just need some thin functionality in the browser, the way you begun can be okay if you're careful. Also, you can still implement the module pattern here too, although I strongly suggest that you should make use of namespacing to have a clear separation of concerns.

Comments

0

Creating a custom JavaScript library is a great deal. For that, you must create a separate Javascript file that would contain all your library code e.g Library.js . You can use this model as an example:

    // Library.js code

    const Utilities= 
    {
      show: function(input)
        {
          alert(input);
        }
    };

  export default Utilities;



// your other JS file where you want to use your library

import Utilities from 'path/to/Library.js';

Utilities.show("hello world!")
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Title of the document</title>
    </head>
    <body>

    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>


    <script src="Library.js"></script>
    </body>
    </html>

This export will export your whole code in Utilities as default so you could easily use all the methods and properties inside Utilities constant .

Comments

-1

In browser based javascript you can't just call functions from different files yet. In Es6 there are ways. But not yet. Which mean just because you have some variable or function etc then you cant reference it automatically in another file.

Unless both files are loaded into one html and are loaded in order.

Alternatively you could run task runner like grunt and 'merge' them upon each build.

Javascript doesnt have special concept of library, in es6 it's a little different, everything is an object.

What you are doing is just creating an object. and yes it will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.