Home / code / javascript

Object References in Javascript

 

Boolean Object

The Boolean Object is a wrapper around the primitive Boolean data type. Use the following syntax to create a Boolean object:

booleanObjectName = new Boolean(value)

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object whose value is not undefined or null, including a boolean object whose value is false, evaluates to true when passed to a conditional statement.

Date Object

JavaScript does not have a data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.

JavaScripthandles dates similarly to Java. The 2 languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970 00:00:00

The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC

To create a Date object:

dateObjectName = new Date([parameters])

where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.

The Parameters in the preceding syntax can be any of the following:

  • Nothing: creates today's date and time. for example, today = new Date()
  • A string representing a date in the following form= "Month day, year hours:minutes:seconds" For example, Xmas95 = new Date("December 25, 1995 13:30:00"). If you omit hours, minutes, or seconds, the value will be set to zero.
  • A set of integer values for year, month and day. For example, Xmas95 = new Date(1995,11,25). A set of values for year, month, day, hour, minute and seconds. For example, Xmas95 = new Date(1995,11,25,9,30,0)
JavaScript 1.2 and earlier versions
  • Dates prior to 1970 are not allowed.
  • JavaScript depends on platform-specific date facilities and behavior; the behavior of the Date object varies from platform to platform.

Methods of the Date Object

The Date object methods for, handling dates and times fall into these broad categories:

  • "set" methods, for setting date and time values in Date objects.
  • "get" methods, for getting date time values from Date objects.
  • "to" methods, for returning string values from Date object.
  • parse and UTC methods, for parsing Date strings.

With the "get and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months and years separately. There is a getDay method the returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:

  • Seconds and minutes: 0 to 59
  • Hours: 0 to 23
  • Day= 0(Sunday) to 6(Saturday)
  • Date: 1 to 31 (day of the month)
  • Months: 0(January) to 11(December)
  • Year: Years since 1900

For example, suppose you define the following date:

Xmas95 = new Date("December 25, 1995")

Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 95

The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970 00:00:00 far a Date object.

For example the following code displays the number of days left in the current year:

today = new Date()
endYear = new Date(2001,11,31,23,59,59,999) //set day and month
endYear.setFullYear(today.getFullYear()) //Set year to this year
msPerDay = PerDay = 24 * 60 * 60 * 1000 //number of milliseconds per day
daysLeft = (endYear.getTime() - today.getTime()) //msPerDay
daysLeft = Math.round(daysLeft) //returns day left in the year

This examples creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days.

The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object:

IPOdate = new Date()
IPOdate.setTime(Date.parse("Aug 9, 1995")

Using the Date Object: Example

In the followingexample, the function JSClock() returns the time in the format of a digital clock.

function JSClock
{
  var time = new Date()
  var hour = time.getHours()
  var minute = time.getMinutes()
  var second = time.getSeconds()
  var temp = "" + ((hour > 12) ? hour - 12 : hour)
  temp += ((minute < 10) ? ":0" : ":") + minute
  temp += ((second < 10) ? ":0" : ":") + second
  temp += (hour >= 12) ? "PM" : "AM")
  return temp
}

The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSecondsmethods assign the value of the current hour, minute and seconds to hour, minute and seconds.

The next 4 statements build a string value based on time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater then 12,(hour - 13), otherwise simply hour.

The next statement appends a minute value to temp If the value of minute is less then 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way.

Finally, a conditional expression appends "PM" to temp if hour is 12 or greater; otherwise, it appends "AM" to temp.

Function Object

The predefined Function object specifies a string of JavaScrip code to be compiled as a function

functionObjectName = new Function ([arg1, arg2, ..., argn], functionBody)

functionObjectName is the name of a variable or a property of an existing object. It can also be an object followed by lowercase event handler name, such as windows.onerror.

arg1, arg2, ... argn are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm".

functionBody is a string specifying the JavaScript code to be compiled as the function body.

Functionobject are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.

In addition to defining functions as described here, you can also use the function statement.

The following code assigns a function to the variable setBGColor. This function sets the current document's background color.

var setBGColor = new Function("document.bgColor='white'")

To call the Functionobject, you can specify the variable name as if it were a function. The following code executes the function specified by setBGColor variable:

var colorChoice="white"
if (colorChoice=="white") (setBGColor())

You can assign the function to an event handler in either of the following ways:

Creating the variable setBGColor shown above is similar to declaring the following function:

function setBGColor()
{
  document.bgColor='white'
}

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:

    The inner function can be accessed only from statements in the outer function The inner function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the inner function.

Math object

The predefined Math object has propertiesand methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi(3.141), which you will use in an application as

Math.PI

Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential and other functions. For example, if you want to use the trigonometric function:

Math.sin(1.56)

Note that all trigonometric methods of Math take arguments in radians

The following table summarizes the Math object methods.

Method Description
abs Absolute value
sin, cos, tan Standard trigonometric functions; argument in radians
acas, asin, atan Inverse trigonometric functions, return values in radians
exp, log Exponential and natural logarithm, base e
ceil Return least integer greater than or equal to argument
floor Returns greatest integer less than or equal to argument
min, max Return greatest or lesser (respectively) of two arguments
pow Exponential; first argument is base, second is exponent
round Round argument to nearest integer
sqrt Square root

Unlike many other objec, you never create a Math object of your own. You always use the predefined Math object.

It is often convenient to use the with statement when a section of code several Math constants and methods, so you don't have to type "Math" repeatedly. For example

with (Math)
{
  a = PI * r * r
  y = r * sin(theta)
  x = r * cos(theta)
}

Number Object

The Number object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:

biggestNum = Number.MAX_VALUE
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaN

You always refer to a property of the predefined Number object shown above, and not as a property of a Number object you create yourself/

The following table summarizes the Number object's properties

Method Description
MAX_VALUE The largest representable number
MIN_VALUE The smallest representable number
NaN Special "not a number" value
NEGATIVE_INFINITY Special infinite value; return on overflow
POSITIVE_INFINITY Special negative infinite value; returned on overflow

String Object

The String object is a wrapper around the string primitive data type. Do not confuse a string literal with the String object. For example, the following code creates the string literal s1 and also the String object s2:

s1 = "foo" //creates a string literal value
s2 = new String("foo") //creates a String object

You can call any of the methods of the String object on a string literal value - Javascript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property withe a string literal.

You should use string literals unless you specifically need to use a String object, because String object can have counterintuitive behavior.
For example:

s1 = "2 + 2" //creates a string literal value
s2 = new String("foo") //creates a String object
eval(s1) //returns the number 4
eval(s2) //returns the string "2 + 2"

A String object has one property, length that indicates the numbers of characters in the string. For example, the following code assigns x the value 13, because "Hello, World!" has 13 characters.

myString = "Hello, World!"
x = mystring.length

A String object has 2 types of methods: those that return a variation on the string itself, such as substring and toUpperCase, and those that return an HTML-formatted version of the string, such as bold and link

For example, using the previous example, both mystring.toUpperCase() and "hello, world!".toUpperCase() return the string "HELLO, WORLD!".

The substring method takes 2 arguments and returns a subset of the string between 2 arguments. Using the previous example, mystring.substring(4, 9) returns the string "o, Wo".

The String object also has a number of methods for automatic HTML formatting, such as bold to create boldface text and link to create a hyperlink.
Example:

mystring.link("http://www.helloworld.com")

The following table summarizes the methods of String object.

Method Description
anchor Creates HTML named anchor
big, blink, bold, fixed, italics, small, strike, sub, sup Creates HTML formatted string
carAt, charCodeAt Returns the character or character code at the specified position in string
indexOf, lastIndexOf Returns the position of specified substring in the string or last position of specified substring, respectively
link Creates HTML hyperlink
concat Combines the text of 2 strings and returns a new string
fromCharCode Constructs a string fromthe specified sequence of ISO-Latin-1 codeset values
split Splits a String object into an array of strings by separating the string into supstrings
slice Extracts a section of an string and returns a new string
substring, substr Returns the specified subset of the string, either by specifying the start and end indexes or the start index and a length
match, replace, search Used to work with regular expressions
toLowerCase, toUpperCase Returns the string in all lowercase or all uppercase, respectively

 

TOP

Latest script:

 

Books: