eval

Evaluates a string of JavaScript code in the context of this object.

Property of

Object

Syntax

eval(string)

Parameters

string

Any string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

Description

The argument of the eval method is a string. If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval at a later point in your script.

eval is also a global function, not associated with any object.

Examples

The following example creates breed as a property of the object myDog, and also as a variable. The first write statement uses eval('breed') without specifying an object; the string “breedis evaluated without regard to any object, and the write method displays Shepherd, which is the value of the breed variable.

The second write statement uses myDog.eval('breed') which specifies the object myDog; the string breed" is evaluated with regard to the myDog object, and the write method displays "Lab", which is the value of the breed property of the myDog object.

function Dog(name,breed,color) {
      this.name=name
      this.breed=breed
      this.color=color
}
myDog = new Dog("Gabby")
myDog.breed="Lab"
var breed='Shepherd'
Console.Write(eval('breed'))
Console.Write(myDog.eval('breed'))

The following example uses eval within a function that defines an object type, stone. The statement flint = new stone("x=42") creates the object flint with the properties x, y, z, and z2. The write statements display the values of these properties as 42, 43, 44, and 45, respectively.

function stone(str) {
      this.eval("this."+str)
      this.eval("this.y=43")
      this.z=44
      this["z2"] = 45
}

flint = new stone("x=42")

Console.Write(flint.x is " + flint.x)

Console.Write(flint.y is " + flint.y)

Console.Write(flint.z is " + flint.z)

Console.Write(flint.z2 is " + flint.z2)