JavaScript

now browsing by category

 

Adding event handlers in loops

JavaScript

Now we’re talking JavaScript.
Let’s consider one example where we want to add a ‘onFocus’ handler to more than one inputs on a web page.
Our handler will just be a simple function that will display a message in a div on the screen.

  	function showMessage(message) {
	    document.getElementById('messageDiv').innerHTML = message;
	}

Now, as you can see, the message is not the same every time, this is why it will be received as an inpot parameter for the function. Here is how we define the messages:

	var allMessages = [
	    {'id': 'name',  'message': "Focus on 'name' input"},
		{'id': 'email', 'message': "Focus on 'email' input"}
	];

This means that we want to show the message “Focus on ‘name’ input” when dealing with the input having id=’name’, and “Focus on ‘email’ input” when dealing with the input having id=’email’. Let’s try to do just that.

function setup() {
	for (var i = 0; i < allMessages.length; i++) {
		var item = allMessages[i];
		document.getElementById(item.id).onfocus = function() {
			showMessage(item.message);
		}
	}
}

Load the html page we just created in a browser and you will notice that it does not do what we expected it to do. No matter what input we set the focus on, the message displayed is always "Focus on 'email' input". (and this is b/c it was the last one in the varAllMessages array).

You might have 2 questions:
1. why is this not working?
2. how do we fix it?

To answer these two questions first we need to understand a how JavaScript scoping works. A a variable's scope (declared with 'var' keyword) is at the function level, not the block level (as we are used from other programming languages), which means that it may only be called (referenced) from within the function in which it is defined. The reason the previous code is not working as expected is because the function we attach to the onfocus event will be run later, not at creation time. And when I say later, I mean is running when the input gets focused on. At that time the for loop finished executing a long time ago, and the variable item's last value is the one "remembered".

The easiest way to fix the code, if using ECMAScript 2015 or newer, is to replace the "var" keyword with "let". So the setup() function becomes:

function setup() {
	for (var i = 0; i < allMessages.length; i++) {
		let item = allMessages[i];
		document.getElementById(item.id).onfocus = function() {
			showMessage(item.message);
		}
	}
}

What changed? Only one tiny word, but the bahavior it beings solves our issue. The explanation is that "var" is scoped to the nearest function block and "let" is scoped to the nearest enclosing block (both are global if outside any block), which in our case is smaller than the function block (it is one iteration of the for loop). So basically using "let" makes variable declaration behave like we are used to from other programming languages like java.

This was a pretty easy fix. But what if I am not using a ECMAScript 2015 or newer? In that case the solution involves closures. Closures are functions that refer to variables that are used locally, but defined in an enclosing scope (function); Basically whenever we use function inside another function, a closure is used.
A closure has a memory block which is allocated when the function starts its execution, and not freed after the function returns. We say that, these functions 'remember' the environment in which they were created. It is like keeping a copy of all the local variables, just as they were when the function exited.

This is the setup() function that solves our problem using closures:

function setup() {
	function buildCallbackFunction(message) {
		var closureFunction = function() {
			// it will remember the value of the 'message' parameter
			showMessage(message);
		};
		return closureFunction;
	}

	for (var i = 0; i < allMessages.length; i++) {
		var item = allMessages[i];
		document.getElementById(item.id).onfocus = buildCallbackFunction(item.message);
	}
}

In our case the "closureFunction" (which can be seen as an equivalent of a java inner class), is a closure function that will remember the value sent to it at creation time, using the "message" parameter.
So the for loop, on its first iteration, will create a closure function by sending allMessages[0].message value to the "message" parameter. These value will be stored in the closure's memory block, and the second iteration (remember, we have an array with length equal 2) of the for loop, even if it changes the variable item's value will not affect the value previously stored in the closure.

Here is also the code for the full html page in case you want to play a little bit with the 3 examples:

<!DOCTYPE html>
<html lang="en">
  <head>
  		<title>Creating closures in loops</title>
  		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
  		<script type="text/javascript">

  			function showMessage(message) {
			    document.getElementById('messageDiv').innerHTML = message;
			}

			var allMessages = [
			    {'id': 'name',  'message': "Focus on 'name' input"},
			    {'id': 'email', 'message': "Focus on 'email' input"}
			];

			function setup() {
				console.log("Setup code goes here");
			};

			function setupWithVar() {
			  for (var i = 0; i < allMessages.length; i++) {
			    var item = allMessages[i];
			    document.getElementById(item.id).onfocus = function() {
			       showMessage(item.message);
			    }
			  }
			}

			function setupWithLet() {
			  for (var i = 0; i < allMessages.length; i++) {
			  	// let keyword was introduced more recently, in ECMAScript 2015,
			    let item = allMessages[i];
			    document.getElementById(item.id).onfocus = function() {
			       showMessage(item.message);
			    }
			  }
			}

			function setupWithClosures() {
				function buildCallbackFunction(message) {
					var closureFunction = function() {
						// it will remember the value of the 'message' parameter
				        showMessage(message);
				    };
				    return closureFunction;
				}

			    for (var i = 0; i < allMessages.length; i++) {
				    var item = allMessages[i];
				    document.getElementById(item.id).onfocus = buildCallbackFunction(item.message);
			    }
			}

  		</script>
  </head>
  <body onload="setup();">
		<div id="messageDiv"> </div>
		<p>Name:  <br/>	<input type="text" id="name" name="name"></p>
		<p>Email: <br/>	<input type="text" id="email" name="email"></p>
  </body>	
</html>

Code Organizing with AMD

JavaScript

Whilst native solutions to these problems may be arriving via ES6
(see ‘modules proposal’), the good news is that writing modular JavaScript can be easily done today, using an implementation of Asynchronous module definition (AMD).

AMD is a JavaScript specification that serves two purposes:

  • defines an API to asynchronously load JavaScript files
  • allows organization of JavaScript code into self contained modules; (each JavaScript file represents a module)

AMD provide the following benefits:

  • Website performance improvements due to loading JavaScript files at runtime (only when they’re needed).
  • Fewer page errors due to not loaded dependencies.
  • Allows developers to encapsulate code in smaller, more logically-organized files in a way similar to other programming languages

The AMD specification is implemented by Dojo Toolkit, RequireJS, and ScriptManJS.
In this article we will take a closer look at RequireJS, which is a popular AMD implementation written by James Burke, a developer who has been quite instrumental in helping shape the AMD module format.

RequireJS helps you to load multiple script files, define modules with or without dependencies, and load in non-script dependencies such as text files.
As an example we will build a simple app that is structured like this:

app
├── libs
│   └── require.js
│   └── jquery.js
│   └── underscore.js
│   └── text.js
├── js
│   └── view
│       └── modelFragment.html
│   └── app.js
│   └── config.js
│   └── AmdModel.js
│   └── AmdCollection.js
└── index.html

In the libs folder we will have all the libraries needed in this project. If you want to follow through and build this example yourself you will have to go to the projects’ websites and download each one of the needed files.

This application will be a single page application (SPA); The only html page used is index.html:

<!-- index.html -->
<!DOCTYPE html>
<html>
    <head>
        <title>Index</title>
        <script data-main="js/config" src="libs/require.js"></script>
    </head>
    <body>
        <h2>AMD models list</h2>
        <div id="container"></div>
    </body>
</html>

As you can see the only javascript file declared is the require.js script. This is the only thing we need. Even though we will also use other files (jquery, underscore, etc), require.js will take care of loading them.
The data-main attribute tells require.js to load js/config.js right after require.js loads. You don’t need much Require.js code to glue your app together. Require.js’s only footprints in your project should be the require and define function calls that are wrapping the contents of each file.
Starting from version 2.0, Require.js also added support for loading non-AMD compatible scripts by using the Shim configuration.

// config.js
requirejs.config({
    //baseUrl: "js",  => b/c of data-main this will be already 'js'
    paths: {
        "jquery": "../libs/jquery",
        "underscore": "../libs/underscore",
        //"smthelese": "http://www.smthelse/script",
        "text": "../libs/text"
    },
    shim: {
        "underscore": {
            deps: [],
            exports: "_"
        }
    },
    waitSeconds: 5
});

As the name implies, the config.js is the javascript code where we configure the Require.js library. You can see in our example, how we tell require.js where dependencies like jquery, underscore or text are located. Under the "path" key we specify the moduleIds as key and the location of the *.js file as value for the key. RequireJS assumes by default that all dependencies are scripts, so it does not expect to see a trailing ".js" suffix on module IDs. RequireJS will automatically add it when translating the module ID to a path.

!!! This example also shows us shim usage for underscore, which is a non-AMD compatible library. 

<br/>
After we setup require.js, for simplicity e kickoff our app from the same script by loading App.js and call the render() method on it.

// Let's kick off the application
require([
  'app'
], function(App){
  App.render();
});

Here ‘app’ is the module id. This module (app.js) is located exactly in the baseDir, this is why it didn’t need an entry in the paths fild in the previously showed configuration. The following is the definition of the ‘app’ AMD module, which is done using the define keyword.

// app.js
define(['jquery', 'underscore', 'AmdCollection'],
    function ($, _, amdCollection) {
        
        render = function() {
            // append the html markup for each model to the div with id 'container'
            _.each(amdCollection, function(amdModel) {

                $('#container').append(
                    amdModel.getHtml()
                );
            });

        };

        return this;

});

We notice that this module has 3 dependencies:

  • jquery: is loaded from the configured path and is assigned to the module scoped variable called ‘$’
  • underscore: is loaded from the configured path and is assigned to the module scoped variable called ‘_’
  • AmdCollection: is loaded from the baseUrl folder and is assigned to the module scoped variable called ‘amdCollection’

The AmdCollection object is a collection/array of models:

// AmdCollection.js
define(['jquery', 'AmdModel'],
    function ($, AmdModel) {

        // just creating a collection with some predefined models
        // in a real app you will probably load these via ajax requests from a server
        return [
            new AmdModel({'label': 'label1', 'value': 'value1'}),
            new AmdModel({'label': 'label2', 'value': 'value2'}),
            new AmdModel({'label': 'label3', 'value': 'value3'}),
            new AmdModel({'label': 'label4', 'value': 'value4'}),
            new AmdModel({'label': 'label5', 'value': 'value5'})
        ]; 

});

The models being used in the AmdCollection are defined like this:

// AmdModel.js
define(['underscore', 'text!view/modelFragment.html'],
    function (_, fragmentTemplate) {

        // PRIVATE variable
        var template = _.template(fragmentTemplate);

        // constructor
        var AmdModel = function(attributes) {
            this.label = (attributes) ? attributes.label : "Undefined";
            this.value = (attributes) ? attributes.value : "";

            this.getHtml = function () {
                // using undescore's template engine
                return template(this);
            };
        };

        return AmdModel;
});

In the AmdModel, the last piece of the puzzle, we’re using a RequireJS/AMD loader plugin for loading text resources.
This is a really nice to have b/c it’s a lot easier using regular HTML tags, instead of building up DOM structures in script.
The modelFragment.html used (repeatedly) by the previous AmdModel module is:

<p>
    <label id="label"> <%= label %> </label>
    <span id="value">  <%= value %> </span>
</p>

It looks very simple. What you see here is a underscore.js template.
The <%= %> syntax is used to print some value in the template. It is going to be replaced at runtime by the values of the object that is being used as parameter. You can read more about the underscore.js tamplates here.

An additional benefit of using Require.js is that it gives you the tools to optimize (concat, minifiy) your entire project using r.js. All you need to do is install either node.js and create a build file; But this is another subject worthy of an entire article.

JavaScript this

JavaScript

In Object Oriented languages, the “this” keyword refers to the current instance of a class.
In JavaScript, a function’s “this” keyword behaves a little different compared to Object Oriented languages. “this” is not assigned a value until an object invokes the function where it is defined. The ECMAScript Standard defines this as a keyword that “evaluates to the value of the ThisBinding of the current execution context”. ThisBinding is something that the JavaScript interpreter maintains as it evaluates JavaScript code, like a special CPU register which holds a reference to an object.
So, the way “this” works is based on invocation, not definition of the function. Because of this it can be different each time the function is called and that’s why it can be very confusing for programmers coming from another OOP language, like java for example.

When we just call a function, defined outside of an object, or in the same scope with the caller code “this” can be:

  • the window object in a browser environment

    console.log(this === window); // true
    
  • the global object in Node environment

    console.log(this === global); // true
    
  • undefined if you’re in strict mode (no implicit binding in this case)

    function testStrict(){
      "use strict"; // see strict mode
      return this;
    }
    console.log(testStrict() === undefined); // true
    

Invoking a function as a method of an object (obj.method()), “this” is the object. This does not mean that functions stored in properties of objects (“methods”) have their “this” bound to the object! Remember, “this” is about invocation, not where it is defined.

var obj = {
    name : 'testObject',
    myMethod : function () {
        console.log("this = "+JSON.stringify(this));
    }
};
obj.myMethod(); // this = {"name": "testObject"}

You can explicitly set “this” as the first parameter of “apply”, “call”, or “bind” built in functions.

var obj1 = {
    name : 'testObject1',
    myMethod : function (param1, param2) {
        //just ignoring the sent parameters
        console.log("this = "+JSON.stringify(this));
    }
};
var obj2 = {
    name : 'testObject2'
}
obj1.myMethod.apply(obj2, [1,2]); // this = {"name":"testObject2"}
obj1.myMethod.call(obj2, 1, 2); // this = {"name":"testObject2"}
obj1.myMethod.bind(obj2, 1, 2); // this = {"name":"testObject2"}

Another rule for binding “this” in JavaScript is when using the “new” operator. A “constructor” in JavaScript is just a regular function used to initialize a newly created object. These “constructor” functions when called using the “new” operator will create a (mostly) empty object, will bind that object to the function being called (sets “this”), and will evaluate to that object (unless the function returns a different object)

function testObject(name) {
    this.name = name;
}

var aVar = new testObject( "dummy" );
console.log( aVar.name ); // dummy

Now, we can summarize the rules for determining this from a function call’s call-site, in their order of precedence. Ask these questions in this order, and stop when the first rule applies.

  1. Is the function called with new (new binding)? If so, “this” is the newly constructed object.
  2. Is the function called with call or apply (explicit binding)? If so, “this” is the explicitly specified object.
  3. Is the function called with a context (implicit binding)? If so, “this” is that context object.
  4. If none of the previous applied, we’re dealing with default binding. If in strict mode, “this” is undefined, otherwise the global object.

ES6 introduces a special kind of function that does not use these rules (see link for more details): arrow-function (also called “fat arrow” operator). These type of functions adopt the this binding from the enclosing scope.

function testFunction() {
    setTimeout(() => {
        // `this` here is lexically adopted from `testFunction()`
        console.log( this.name );
    }, 100);
};

var obj1 = {
    name: 'dummy'
};

testFunction.call( obj1 ); // 'dummy'

In the wild, you will not see fat arrows very often. Instead there is a fairly common pattern for achieving the same thing.

function testFunction() {
    var _self = this; // lexical capture of `this`
    setTimeout( function() {
        console.log( _self.name );
    }, 100 );
};

var obj1 = {
    name: 'dummy'
};

testFunction.call( obj1 ); // 'dummy'

Recognizing text retrieved via Jcrop

Java

This is our scenario. We have an image loaded on a web page. The image contains written text.
We want to use Jcrop to highlight the portion of text, and send it to a server API that runs an OCR engine, in order to extract the text we’re interested from the image.
In our example we will use tesseract-ocr, a free software, released under the Apache License, sponsored by Google since 2006. We have another article where we used this engine for doing localized ocr (here)

Here is the html page that also contains the javascript code required for cropping and calling the server side API:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Home Page</title>
        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="//jcrop-cdn.tapmodo.com/v0.9.12/js/jquery.Jcrop.min.js"></script>
        <link rel="stylesheet" href="//jcrop-cdn.tapmodo.com/v0.9.12/css/jquery.Jcrop.css" type="text/css" />
        <script type="text/javascript">

            jQuery(function ($) {

                $("#ocrButton").click(function (event) {
                    event.preventDefault();
                    $.ajax(
                            {
                                type: 'GET',
                                url: "${pageContext.servletContext.contextPath}/partialOcr",
                                data: {
                                    'x1': $('#x1').val(),
                                    'y1': $('#y1').val(),
                                    'width': $('#width').val(),
                                    'height': $('#height').val(),
                                    'imageId': 'Invoice2.png'
                                },
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                // crossDomain: true,
                                timeout: 9500,
                                success: function (data) {
                                    console.log("data: " + data);
                                    $("#ocrResult").val(data);
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    console.log(jqXHR.status + ' ' + textStatus + '\n ' + jqXHR.responseText);
                                    window.alert(jqXHR.responseText);
                                }
                            }
                    );
                });

                var jcrop_api;

                $('#target').Jcrop({
                    boxWidth: 727,
                    boxHeight: 1000,
                    onChange: showCoords,
                    onSelect: showCoords,
                    onRelease: function () {
                        $('#coords input').val('');
                    }
                }, function () {
                    jcrop_api = this;
                });

                $('#coords').on('change', 'input', function (e) {
                    var x1 = $('#x1').val(), x2 = $('#x2').val(), y1 = $('#y1').val(), y2 = $('#y2').val();
                    jcrop_api.setSelect([x1, y1, x2, y2]);
                });

            });

            // Simple event handler, called from onChange and onSelect event handlers, as per the Jcrop invocation above
            function showCoords(c) {
                $('#x1').val(c.x);
                $('#y1').val(c.y);
                $('#x2').val(c.x2);
                $('#y2').val(c.y2);
                $('#width').val(c.w);
                $('#height').val(c.h);
            };

        </script>
    </head>
    <body>

        <table>
            <tr>
                <td>
                    <div>
                        <img src="${pageContext.servletContext.contextPath}/images/Invoice.png" id="target"/>
                    </div>
                </td>
                <td valign="top">
                    <input id="ocrButton" type="button" value="OCR"/>    

                    <br/><br/>

                    <textarea id="ocrResult">
                        ${ocrResult}
                    </textarea>
                </td>
            </tr>
        </table>

        <div id="coords" class="coords">

            <div class="inline-labels">

                <label>X1 
                    <input type="text" size="4" id="x1" name="x1" />
                </label>
                <label>
                    Y1 <input type="text" size="4" id="y1" name="y1" />
                </label>
                <label>
                    X2 <input type="text" size="4" id="x2" name="x2" />
                </label>
                <label>
                    Y2 <input type="text" size="4" id="y2" name="y2" />
                </label>
                <label>
                    W <input type="text" size="4" id="width" name="width" />
                </label>
                <label>
                    H <input type="text" size="4" id="height" name="height" />
                </label>

            </div>
        </div>


    </body>
</html>

Notice that we will also display the coordinates for our selection on our page. When we click the “OCR” button, these coordinates will be sent as request parameters together with an identifier for the image we’re dealing with. (In our case, an invoice). The server code will run OCR on the same image, at the coordinates it receives, and it will return a json with the ocr result. Here is the java server side piece:

import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.codehaus.jackson.map.ObjectMapper;

@WebServlet("/partialOcr")
public class LocalizedOcrServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {

        System.out.println("START OCR on image");

        String x1Param = request.getParameter("x1");
        String y1Param = request.getParameter("y1");
        String widthParam = request.getParameter("width");
        String heightParam = request.getParameter("height");
        String imageIdParam = request.getParameter("imageId");

        int x1 = (int) Double.parseDouble(x1Param);
        int y1 = (int) Double.parseDouble(y1Param);
        int width = (int) Double.parseDouble(widthParam);
        int height = (int) Double.parseDouble(heightParam);

        String pathToWebImages = getServletContext().getRealPath(File.separator + "images");
        File imageFile = new File(pathToWebImages, imageIdParam);
        System.out.println("imageFile=" + imageFile.getAbsolutePath());

        try {

            Tesseract tesseract = Tesseract.getInstance();
            tesseract.setTessVariable("TESSDATA_PREFIX", "/usr/include/tesseract");

            tesseract.setDatapath("/usr/share/tessdata/");
            String ocrResult = tesseract.doOCR(
                    ImageIO.read(imageFile),
                    new Rectangle(x1, y1, width, height)
            );
            System.out.println("ocrResult=" + ocrResult);
            ocrResult = (ocrResult != null) ? ocrResult.trim() : null;
            
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "private");
            response.setContentType("application/json");

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), ocrResult);

            response.flushBuffer();
        } catch (IOException | TesseractException ex) {
            ex.printStackTrace();
            try {
                response.sendError(200, ex.getMessage());
            } catch (IOException ex1) {
            }
        }

    }

}

Notice that we are using tess4j, which is a JNA wrapper for Tesseract OCR API.

Creating your own JavaScript Namespace

JavaScript

JavaScript is an interpreted computer programming language that was originally intended to do small tasks in webpages. JavaScript is the only language that is found in all major web browsers and it is used to create client-side scripts that can interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed.

One of the biggest problem of the JavaScript language is its dependence on global variables, particularly implied global variables. Unlike in other popular programming languages like Java or C, in JavaScript, blocks do not introduce a scope. There is only function-scope. A variable introduced anywhere in a function is visible everywhere in the function.  Developers needs to be extra careful and declare explicitly all the variables (usually with the var statement), because if a variable is not explicitly declared , then JavaScript assumes that the variable is global.

The window object represents an open window in a browser. The window object is supported by all browsers, and it basically becomes the global container for the JavaScript objects => all global JavaScript objects, functions, and variables automatically become members of the window object.

In order to avoid any naming collisions that can occur in the global space when a lot of scripts are being imported on a page you should create a single global variable that will become the container for your application. By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.

The following is an example of how to do this. We will start by creating javascript file named namespeceTest.js that will have the following content:


var MyNamespace = ( function () {
   var privateValue = 0;
   var printValuePrivate = function ( ) {
         if (console) {
              console.log("value = " + privateValue);
         }
   };
   return { /*code block that returns an object literal*/
           setValue: function (newValue) {
               privateValue = newValue;
           },
           getValue: function ( ) {
               return privateValue;
           },
           printValue: function ( ) {
               printValuePrivate ( ) ; 
           }
     };
}());

window.MyNamespace = MyNamespace;

What is worth understanding here is that the variable MyNamespace is not actually assigned a function object, but the result of invoking that function => see ( ) at the end

So, instead of initializing MyNamespace with an object literal, we are initializing MyNamespace by calling a function that returns an object literal (see commented return statement).

The function returns an object containing three methods, and those methods continue to enjoy the privilege of access to the privateValue variable (and printValuePrivate function).

These functions will be available from “outside”, so calls of type: MyNamespace.getValue() or MyNamespace.setValue(10) are perfectly legal.

Because of the function-scope we talked earlier, the privateValue variable and the printValuePrivate function defined in the main function, are always available to the setValue, getValue and printValue methods, but the function’s scope keeps them hidden from the rest of the program. This technique can be also seen as a way to encapsulate your objects, without using keywords like private/public which are not available in JavaScript.

The last line of code in the javascript file is also very important  

window.MyNamespace = MyNamespace;

because it will assign our container object MyNamespace to the window javascript object, so we can actually use it inside a testing html page


<html>
	<head>
		<title>Namespace Test</title>
		<script src='namespaceTest.js'></script>
	</head>
	<body>
	   <script>
             document.writeln("Getting 'undefined' when trying to access variable privateValue directly. MyNamespace.privateValue = ' " + MyNamespace.privateValue + "'</br>");
             //document.writeln("Calling MyNamespace.printValuePrivate() is not allowed ... => Error </br>");
             //MyNamespace.printValueHidden();
             document.writeln("Show initial privateValue by calling MyNamespace.getValue() = " + MyNamespace.getValue() + "</br>");
             document.writeln("Calling MyNamespace.setValue(10) ...</br>");
             MyNamespace.setValue(10) ;
             document.writeln("Calling MyNamespace.getValue() = " + MyNamespace.getValue() + "</br>");
             document.writeln("Calling MyNamespace.printValue() ... </br>");
             MyNamespace.printValue();
 	   </script>
	</body>
</html>