I seize him with a terrific struggle. His great will and power are inexhaustible. He charges to the high plateau far above the cloud-mists, Or in an impenetrable ravine he stands. |
We'll use this example to introduce a ubiquitous JavaScript method, eval(),and clarify the business of addressing that we visited at the end of the last tutorial page. [The HTML code is capitalized to make it easy to distinguish from the lower-case JavaScript].
eval() has many meanings. In this case, it resolves a mathematical string, returning the answer. Just the thing for a calculator! So eval("6*3/2") returns 9.
When you use the calculator, it builds a string of mathematical symbols - numbers and operators. Pressing the equals button turns the mathematical string into a string holding the results of the eval method. Click the key to see the compute(obj) function. [Don't worry about how the string is built or updated. We'll get to that].
Buttons and 'this':
The Calculator is a simple html table containing buttons and a text box inside of a form . JavaScript makes it 'work'. Recall that there are two places where you see JavaScript code - in the heading as variables and functions, and in the body as JavaScript strings in event handlers. Here are a few lines from the Calculator code shown in isolation for clarity - the compute(obj) function, the text box, and the code for the one, minus, clear, and equal buttons:
What about the equals button? What we want to say is, "Using eval, replace the mathematical string in the text box with the answer". Couldn't we have written this?
this.form is passed to compute(obj) - meaning that the parameter obj now holds this.form. What is it that has been passed? Remember back in Tutorial Two that a variable may hold a number, a string, or an object - and that a function's parameter is a local variable. So obj holds a reference to the calculator form object. Now the code in compute(...) should make sense.