MyName = new String("Ian Rogers");
You can use the Function constructor to create functions without a name, anonymous functions. You employ this technique whenever you need to construct a function dynamically, "on the fly". An anonymous function can be assigned to a variable.
isBetween = new Function("a", "b", "c", "if((a>=b)&&(a<=c))return(true);else return(false);");
document.write(isBetween(5, 1, 10));
document.write(isBetween(15, 1, 10));
In the example above, the anonymoys function evaluates if the value of the number a falls between b and c, and returns true if it does, or false otherwise.
"a", "b", and "c" are parameters. Each parameter in the list in enclosed in quotes.
Lastly, the body of the function is enclosed in quotes.
Below is a traditional way of writing a function to do the same thing.
function isBetween(a, b, c)
if((a>=b) && (a<=c)) return(true);
As an exercise, write a function isPointInRect(x, y, top, left, bottom, right); to calculate if the point x,y falls within the rectangle denoted by the upper-left and lower-right points: top, left, bottom, right. When you are finished, convert the function into an anounymous one.
To write your own constructors, you use the this keyword within the constructor to refer to the newly-created object. The constructor initializes the object.
In the example below:
The make7Table constructor creates a multiplication table for number 7
The size property is introduced to keep track of the number of elements
The value of each element is initialized
this.size = numElements;
for(cnt = 0; cnt < numElements; cnt++)
this[cnt] = cnt*7;
// Use the constructor to create and initialize an array.
myArray = new make7Table(10);
document.write("This table has " + myArray.size + " elements");
The example below adds the baseSalary property to the Math object. From this moment on, the new property is available to the rest of the program.
Math.baseSalary = 50000;
return (Math.baseSalary + bonus);
document.write("Total salary: " + calculateSalary(10000));