Time for action – modularizing our program

Now we are going to modularize our software.

  1. Let's create a new file called hello-world-module.js and fill it with this:
    #!/usr/bin/env seed
    
    print("Hello world")
    
    
    var BookModule = imports.book
    
    var book = new BookModule.Book("1234", "A good title");
    book.printTitle();
    book.printISBN();
  2. Create another new script called book.js and fill it with this:
    var Book = function(isbn, title) {
      this.isbn = isbn;
      this.title = title;
    }
    
    Book.prototype = {
      printTitle: function(){
        print("Title is " + this.title);
      },
    
      printISBN: function() {
        print("ISBN is " + this.isbn);
      }
    }
  3. Then run hello-world-module.js (not book.js).
  4. See the printouts.

From the output, we can see that it is exactly the same as the previous code. But here we split the code into two files.

Here, we ask Seed to attach the BookModule variable with the evaluation of book with the imports command. Here it is expected that we have book.js inside our current directory. With this, all objects in book.js are accessible from the BookModule variable. Hence, we construct the book object with the previous line.

Also note that, in book.js, we no longer have the hashbang line. This is not required because we don't use book.js as our entry point, but rather we use hello-world-module.js.

With this approach, we can lay out our objects in files and import them whenever necessary. This not only makes the memory usage efficient but also keeps the code structure clean.

This concludes our quick introduction to JavaScript as a GNOME application development programming language. Now let's move on to Vala.