Next page | Contents page |

The global object - and a WARNING

An anonymous object of type Global is created by the JavaScript interpreter (eg, browser) when it starts executing your code. It is "the current object" when you are not in another object's constructor or method (or in an event handler, as we will see later). You can therefore prefix the names of properties and methods of the global object with this for clarity if you wish, though that is rarely done. (In web client JavaScript this will be the object representing the current window. We will cover that in the next section of the course.)

NB: All variables you declare outside functions are properties of the global object. You can list them by using

  for (var x in this) 

If you are working in a system with many separate sections of script there is a risk of name clashes between global variables, so be extra careful with naming. You can use the loop example above to find out what names have already been used.

The global object has several useful methods, some of which we have met already:

var a = parseInt ("123.45e3");// Stops converting at non-digit
var b = parseInt ("023");     // Initial 0 means octal, -> 19 decimal
var c = parseInt ("023", 10); // Optional radix 10 forces decimal -> 23
var d = parseFloat ("1.2e10 is a number"); // Stops at space
var e = isNaN (b);
var f = unescape ("Hello World!");  // -> "Hello%20World%21"
var g = escape (f);
var x = eval ("Math.sqrt (3 * 3 + 4 * 4)");  // -> 5

unescape() and escape() and, for URIs, decodeURI() and encodeURI(), enable strings to be passed between web clients and servers over HTTP by replacing all punctuation characters, including spaces, with % followed by 2 hexadecimal digits which are their ASCII character codes.

WARNING - eval()

In the list of methods above you may have noticed eval(). It's neat: given a String it interprets and executes it as JavaScript. The example we used was an innocent bit of arithmetic. But it could be a much bigger chunk of JavaScript, containing statements, functions, object constructors and so on. eval() would execute that.

On an HTML page such as we considered in Part 1 what would happen if a malicious user typed into an input field, eval(...) containing executable statements? Can you be certain it will not get executed at some stage?

So eval() is powerful but dangerous.

To protect against such a thing it is absolutely vital ALWAYS TO VALIDATE user inputs. We will return to this in the next part of the course.

It gets worse too: attackers can embed SQL commands in input text, to extract data from databases on web servers unless your field validation stops that.

ALWAYS VALIDATE USER INPUT - only accept the characters you are expecting. Eg, a person's name might contain the letter sequence "eval" but it would not contain any kind of brackets.

Using eval()

With understanding of the warning above it may now be safe for you to use eval() in a local HTML page. It is quite easy to make a very useful command box that enables you to enter JavaScript statements as commands for immediate execution. The code follows. Try it.


<!-- saved from url=(0014)about:internet -->
    <script type="text/javascript" src="command.js"></script>
    <textarea id="text" onkeypress="void key (event)"
      cols="40" rows="20">script:</textarea>

Note the HTML element <textarea> which we had not used before.


var PROMPT = "script:";
// An angle bracket to end the prompt
// would add complications.

function key (ev)
  var code;

  if (window.event) // IE
    ev = window.event;
    code = ev.keyCode;
    ev.cancelBubble = true;
  else if (ev.which) // Other browsers
    code = ev.which;
    ev.stopPropagation ();

  if (13 == code) // Enter key
    ev.returnValue = false; // IE

    if (ev.preventDefault) ev.preventDefault ();
	// To make the cursor stay at the line end
	// after execute(), rather than doing the
	// Enter as typed by the user.

    execute ();
} // key

function execute ()
  var el = document.getElementById ("text");
  var s = el.value;
  var i = s.lastIndexOf (PROMPT);

  if (i > -1)
    s = s.substring (i + 2);
    el.value += "\n=" + eval (s) + "\n" + PROMPT;
} // execute
Next page | Contents page |