home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


JavaScript: The Definitive Guide

Previous Chapter 21
JavaScript Reference
Next
 

Object.eval() Method

Name

Object.eval() Method---evaluate JavaScript code in a string

Availability

Navigator 2.0, Internet Explorer 3.0; modified in Navigator 3.0

Synopsis

eval(code)    Navigator 2.0, Internet Explorer 3.0
object.eval(code)   Navigator 3.0

Arguments

code

A string that contains the JavaScript expression to be evaluated or the statements to be executed.

Returns

The value of the evaluated code, if any.

Description

In Navigator 2.0 and Internet Explorer 3.0, eval() is a built-in function (i.e., not a method of any object), but it behaves as if it is a method of the Window object. In Navigator 3.0, eval() has become a method of Object, so it can be invoked through a JavaScript object of any type.

eval() executes the JavaScript code in its string argument code. code may contain one or more JavaScript statements. If there is more than one statement, they must be separated from each other by semicolons. Recall that JavaScript expressions are themselves a simple type of statement, so you can also use eval() to evaluate a JavaScript expression rather than execute a statement. eval() returns the value of the last expression in code that it evaluates. If code contains only statements that have no value, eval() returns nothing.

In Navigator 2.0 and Internet Explorer 3.0, eval() evaluates the specified code in the context of the current Window object. In Navigator 3.0, it evaluates the code in the context of the object through which it is invoked. Thus, in Navigator 3.0, when you use eval() without an object specified to its left, it is implicitly invoked through the current window object, and its behavior is the same as in Navigator 2.0.

But in Navigator 3.0, eval() can also be invoked through other objects:

var x = 1;
o = new Object();
o.x = 2;
o.eval('x');  // evaluated in o's context; returns 2
eval('x');    // evaluated in Window context; returns 1

Usage

eval() provides the capability for a JavaScript program to dynamically modify the code that it executes. It gives you the ability to write a JavaScript program that acts as a JavaScript interpreter. In practice, eval() is not frequently used. In most cases, you can do anything you want with a statically defined function.

Bugs

eval() crashes Navigator 2.0 on 16-bit Windows (Windows 3.1) platforms. A workaround that is possible in some cases is to use Window.setTimeout() with a zero-millisecond delay as a replacement for eval().


Previous Home Next
Object.constructor Book Index Object.prototype

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell