spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / java_core / 2 To page 1To page 2To page 3To page 4To page 5current page
[previous]

Sr Instructional Designer D2L-Moodle,Clearance
WSI Nationwide, Inc.
US-NJ-Fort Monmouth

Justtechjobs.com Post A Job | Post A Resume
Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs


JavaScript by Example: JavaScript Core Objects. Pt. 2

The Function Object

The Function object (added in JavaScript 1.1) lets you define a function as an object dynamically. It allows a string to be defined at runtime and then compiled as a function. You can use the Function() constructor to create a variable that contains the function. Since the function has no name, it is often called an anonymous function and its arguments are passed as comma-separated strings. The last argument is the body of statements that will be executed when the function is called. If the Function() constructor does not require arguments, then the body of statements, treated as a string, will be passed to the Function() constructor to define what the function is to do. Since functions are objects, they also have properties (see Table 9.13) and methods (see Table 9.14).


Function objects are evaluated each time they are used, causing them to be slower in execution than normal JavaScript functions.


Properties of the Function object.

Property

What It Does

length

Returns the number of arguments that are expected to be passed (read only)

prototype

Allows the object to be customized by adding new properties and methods


Methods of the Function object.

Property

What It Does

apply()*

Allows you to apply a method from one function to another

call()

Allows you to call a method from another object

* Supported on versions Netscape 4.06+ and Internet Explorer 5.5+.

 

 

var nameOfFunction = new Function (arguments, statements_as_string: }

 

Example Function Definition:

 

var addemUp = new Function ( "a", "b", "return a + b;" );

 

Example Function Call:

 

document.write(addemUp (10, 5));

 

 

<html><head><title>Function Object</title>

</head>

<body bgcolor=lightgreen>

<font face="arial" size="+1">

<center>

Anonymous Functions and the Function Constructor<p>

<script language="JavaScript">

1 var sum = new Function("a","b", "return a + b; ");

2 window.onload = new Function ( "document.bgColor='yellow';");

3 document.write( "The sum is " + sum(5,10)+ "<br>");

document.write( "The background color is yellow<br>");

</script>

</body></html>

 

 
A variable called sum is a Function object, created by the Function() constructor. It has two arguments, "a" and "b". The function statements are the last string in the list. These statements will be executed when the function is called.

  1. This Function() constructor only has one argument, the statement that will be executed when the function is called. Since the function is assigned to the onload event method for the window object, it will act as an event handler and cause the background color to be yellow when the document has finished loading.

  2. The sum function is called with two arguments. (See Figure 9.32.)

The with Keyword Revisited

In Chapter 8, we used the with keyword with user-defined objects to make it easier to manipulate the object properties. Recall that any time you reference the object within the block following the keyword, you can use properties and methods without the object name. This saves a lot of typing and reduces the chances of spelling errors, especially when the properties have long names. The String object is used in the following example to demonstrate how with is used.

 

<html><head><title>The with Keyword</title>

</head>

<body>

<h2>Using the <em>with</em> keyword</h2>

<p>

<h3>

<script language="JavaScript">

var yourname=prompt("What is your name? ","");

// Create a string object

with(yourname){

document.write("Welcome " + yourname + " to our planet!!<br>");

document.write("Your name is " + length + " characters in

length.<br>");

document.write("Your name in uppercase: " + toUpperCase() +

".<br>");

document.write("Your name in lowercase: " + toLowerCase() +

".<br>");

}

</script>

</h3>

</body></html>

 

Using the with keyword to reference an object.

Exercises
  1. Create an array of five animals. Use a for loop to display the values stored there. Now add two more animals to the end of the array and sort the array. (Use JavaScript's built-in array methods.) Display the sorted array.
  2. Create an associative array called colors. Each element of the array is a string representing the color, e.g., red or blue. Use the for/in loop to view each element of the array with a color of the font the same color as the value of the array element being displayed.
  3. Create a function that will return the current month by its full name. Use the Date object to get the current month. Months are returned as 0 for January, 1 for February, 2 for March, etc. Output should resemble:

    The current month is January.

    Hint: You can create an array, starting at index 0, and assign a month value to it; e.g., month[0]="January" or use a switch statement, e.g., case 0: return "January".
  4. An invoice is due and payable in 90 days. Write a function that will display that date.
  5. How many days until your birthday? Write a function to calculate it.
  6. To calculate the balance on a loan, the following formula is used:
  7. PV = PMT * ( 1 - (1 + IR )-NP) / IR
  8. PV is the present value of the loan; PMT is the regular monthly payment of the loan; IR is the loan's interest rate; NP is the number of payments remaining.
    Write a JavaScript statement to represent this formula.
  9. Using the formula to calculate the loan balance from the last exercise, write a function that will calculate the principle balance left on a loan where the monthly payments are $600, the annual interest rate is 5.5%, and there are 9 years remaining on the loan. Use the toFixed() Number method to format the output.
  10. Apply the ceil(), floor(), and round() methods to the number 125.5567 and display the results.
  11. Create an array of 10 fortune cookies that will be randomly displayed each time the user reloads the page.
  12. Create a string prototype that can be used to create an italic, Verdana font, point size 26.
  13. Calculate the circumferance of a circle using the Math object.
  14. Write a JavaScript program that uses the Array and Math objects. Create an array of 5 sayings, for example: "A stitch in time saves 9", or "Too many cooks spoil the broth". Each time the Web page is visited, print a random saying.

 

  1. Use the Date object to print today's date in this format:

    Today is Friday, June 16, 2003.
  2. Calculate and display the number of days until your next birthday.
  3. Create a prototype for the Date object that will print the months starting at 1 instead of 0.

 

  1. Create a String object containing "Jose lived in San Jose for many years."
  2. Find the index for the second Jose.
  3. Get the substring ear from years.
  4. Display the string in a blue, italic font, point size 12, all uppercase.

1. Creating a multidimensional array (i.e., an array with more than one index) is not officially supported by JavaScript, but can be simulated with some trickery.

2. Arrays were introduced in JavaScript 1.1.

3. For more information about the time and date, see http://www.timeanddate.com/worldclock/.

4. Greenwich Mean Time (GMT) is now called Universal Coordinate Time (UTC). The current time in Greenwich, England is five hours + New York's present time, or eight hours + San Francisco's present time.

5. These methods are part of the ECMA 3.0, IE5.5+, Netscape 6.0+.


home / programming / java_core / 2 To page 1To page 2To page 3To page 4To page 5current page
[previous]

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint

Created: March 27, 2003
Revised: November 19, 2003

URL: http://webreference.com/programming/java_core/2