0% found this document useful (0 votes)
123 views23 pages

Introduction to JavaScript Objects

The document provides information about JavaScript objects and their usage. It introduces several built-in JavaScript objects - String, Date, Array, Boolean, Math, and RegExp objects. For each object, it describes how to create it using the constructor, some example properties and methods, and basic usage examples to manipulate or get values from the objects.

Uploaded by

Rajeev
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Topics covered

  • JavaScript Syntax,
  • Boolean Object,
  • JavaScript Standards,
  • JavaScript Templates,
  • JavaScript Internationalizatio…,
  • Timing Events,
  • JavaScript Libraries,
  • JavaScript Development Tools,
  • Form Validation,
  • ASP
0% found this document useful (0 votes)
123 views23 pages

Introduction to JavaScript Objects

The document provides information about JavaScript objects and their usage. It introduces several built-in JavaScript objects - String, Date, Array, Boolean, Math, and RegExp objects. For each object, it describes how to create it using the constructor, some example properties and methods, and basic usage examples to manipulate or get values from the objects.

Uploaded by

Rajeev
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Topics covered

  • JavaScript Syntax,
  • Boolean Object,
  • JavaScript Standards,
  • JavaScript Templates,
  • JavaScript Internationalizatio…,
  • Timing Events,
  • JavaScript Libraries,
  • JavaScript Development Tools,
  • Form Validation,
  • ASP

JavaScript Objects Introduction

JavaScript is an Object Oriented Programming (OOP) language.

An OOP language allows you to define your own objects and make your own variable types.

Object Oriented Programming

JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own
objects and make your own variable types.

However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by
looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in
JavaScript object in detail.

Note that an object is just a special kind of data. An object has properties and methods.

Properties

Properties are the values associated with an object.

In the following example we are using the length property of the String object to return the number of characters
in a string:

<script type="text/javascript">
var txt="Hello World!";
[Link]([Link]);
</script>

The output of the code above will be:

12

Methods

Methods are the actions that can be performed on objects.

In the following example we are using the toUpperCase() method of the String object to display a text in uppercase
letters:

<script type="text/javascript">
var str="Hello world!";
[Link]([Link]());
</script>

The output of the code above will be:

HELLO WORLD!

JavaScript String Object


The String object is used to manipulate a stored piece of text.

String object

The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a string:

var txt="Hello world!";


[Link]([Link]);

The code above will result in the following output:

12

The following example uses the toUpperCase() method of the String object to convert a string to uppercase letters:

var txt="Hello world!";


[Link]([Link]());

The code above will result in the following output:

HELLO WORLD!

JavaScript Date Object

The Date object is used to work with dates and times.

Create a Date Object

The Date object is used to work with dates and times.

Date objects are created with the Date() constructor.

There are four ways of instantiating a date:

new Date() // current date and time


new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

Most parameters above are optional. Not specifying, causes 0 to be passed in.

Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and
set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC
(universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 [Link] Universal Time (UTC) with a day
containing 86,400,000 milliseconds.

Some examples of instantiating a date:

today = new Date()


d1 = new Date("October 13, 1975 [Link]")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)

Set Dates

We can easily manipulate the date by using the methods available for the Date object.

In the example below we set a Date object to a specific date (14th January 2010):

var myDate=new Date();


[Link](2010,0,14);

And in the following example we set a Date object to be 5 days into the future:

var myDate=new Date();


[Link]([Link]()+5);

Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date
object itself!

Compare Two Dates

The Date object is also used to compare two dates.

The following example compares today's date with the 14th January 2010:

var myDate=new Date();


[Link](2010,0,14);
var today = new Date();

if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}

JavaScript Array Object

The Array object is used to store multiple values in a single variable.


What is an Array?

An array is a special variable, which can hold more than one value, at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

cars1="Saab";
cars2="Volvo";
cars3="BMW";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but
300?

The best solution here is to use an array!

An array can hold all your variable values under a single name. And you can access the values by referring to the
array name.

Each element in the array has its own ID so that it can be easily accessed.

Create an Array

An array can be defined in three ways.

The following code creates an Array object called myCars:

1:

var myCars=new Array(); // regular array (add an optional integer


myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";

2:

var myCars=new Array("Saab","Volvo","BMW"); // condensed array

3:

var myCars=["Saab","Volvo","BMW"]; // literal array

Note: If you specify numbers or true/false values inside the array then the variable type will be Number or
Boolean, instead of String.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The
index number starts at 0.

The following code line:


[Link](myCars[0]);

will result in the following output:

Saab

Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:

myCars[0]="Opel";

Now, the following code line:

[Link](myCars[0]);

will result in the following output:

Opel

JavaScript Boolean Object

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

Create a Boolean Object

The Boolean object represents two values: "true" or "false".

The following code creates a Boolean object called myBoolean:

var myBoolean=new Boolean();

Note: If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the object is set to
false. Otherwise it is true (even with the string "false")!

All the following lines of code create Boolean objects with an initial value of false:

var myBoolean=new Boolean();


var myBoolean=new Boolean(0);
var myBoolean=new Boolean(null);
var myBoolean=new Boolean("");
var myBoolean=new Boolean(false);
var myBoolean=new Boolean(NaN);

And all the following lines of code create Boolean objects with an initial value of true:
var myBoolean=new Boolean(true);
var myBoolean=new Boolean("true");
var myBoolean=new Boolean("false");
var myBoolean=new Boolean("Richard");

JavaScript Math Object

The Math object allows you to perform mathematical tasks.

Math Object

The Math object allows you to perform mathematical tasks.

The Math object includes several mathematical constants and methods.

Syntax for using properties/methods of Math:

var pi_value=[Link];
var sqrt_value=[Link](16);

Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object
without creating it.

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E, PI,
square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.

You may reference these constants from your JavaScript like this:

Math.E
[Link]
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there are also several
methods available.

The following example uses the round() method of the Math object to round a number to the nearest integer:

[Link]([Link](4.7));

The code above will result in the following output:

5
The following example uses the random() method of the Math object to return a random number between 0 and 1:

[Link]([Link]());

The code above can result in the following output:

0.8999487253222361

The following example uses the floor() and random() methods of the Math object to return a random number
between 0 and 10:

[Link]([Link]([Link]()*11));

The code above can result in the following output:

JavaScript RegExp Object

RegExp, is short for regular expression.

What is RegExp?

A regular expression is an object that describes a pattern of characters.

When you search in a text, you can use a pattern to describe what you are searching for.

A simple pattern can be one single character.

A more complicated pattern can consist of more characters, and can be used for parsing, format checking,
substitution and more.

Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.

Syntax
var txt=new RegExp(pattern,modifiers);

or more simply:

var txt=/pattern/modifiers;

• pattern specifies the pattern of an expression


• modifiers specify if a search should be global, case-sensitive, etc.

RegExp Modifiers

Modifiers are used to perform case-insensitive and global searches.

The i modifier is used to perform case-insensitive matching.


The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

Example 1

Do a case-insensitive search for "w3schools" in a string:

var str="Visit W3Schools";


var patt1=/w3schools/i;

The marked text below shows where the expression gets a match:

Visit W3Schools

Example 2

Do a global search for "is":

var str="Is this all there is?";


var patt1=/is/g;

The marked text below shows where the expression gets a match:

Is this all there is?

Example 3

Do a global, case-insensitive search for "is":

var str="Is this all there is?";


var patt1=/is/gi;

The marked text below shows where the expression gets a match:

Is this all there is?

test()

The test() method searches a string for a specified value, and returns true or false, depending on the result.

The following example searches a string for the character "e":


Example
var patt1=new RegExp("e");
[Link]([Link]("The best things in life are free"));

Since there is an "e" in the string, the output of the code above will be:

true

exec()

The exec() method searches a string for a specified value, and returns the text of the found value. If no match is
found, it returns null.

The following example searches a string for the character "e":

Example 1
var patt1=new RegExp("e");
[Link]([Link]("The best things in life are free"));

Since there is an "e" in the string, the output of the code above will be:

JavaScript Browser Detection

The Navigator object contains information about the visitor's browser.

Browser Detection

Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are some things that
just don't work on certain browsers - especially on older browsers.

Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate information.

The best way to do this is to make your web pages smart enough to look one way to some browsers and another
way to other browsers.

The Navigator object contains information about the visitor's browser name, version, and more.

Note: There is no public standard that applies to the navigator object, but all major browsers support it.

The Navigator Object

The Navigator object contains all information about the visitor's browser:
Example
<html>
<body>

<script type="text/javascript">
[Link]("Browser CodeName: " + [Link]);
[Link]("<br /><br />");
[Link]("Browser Name: " + [Link]);
[Link]("<br /><br />");
[Link]("Browser Version: " + [Link]);
[Link]("<br /><br />");
[Link]("Cookies Enabled: " + [Link]);
[Link]("<br /><br />");
[Link]("Platform: " + [Link]);
[Link]("<br /><br />");
[Link]("User-agent header: " + [Link]);
</script>

</body>
</html>

JavaScript Cookies

A cookie is often used to identify a user.

What is a Cookie?

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a
browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

Examples of cookies:

• Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The
name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome
message like "Welcome John Doe!" The name is retrieved from the stored cookie
• Password cookie - The first time a visitor arrives to your web page, he or she must fill in a password. The
password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved
from the cookie
• Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next
time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday
August 11, 2005!" The date is retrieved from the stored cookie

Create and Store a Cookie

In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web
page, he or she will be asked to fill in her/his name. The name is then stored in a cookie. The next time the visitor
arrives at the same page, he or she will get welcome message.

First, we create a function that stores the name of the visitor in a cookie variable:

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
[Link]([Link]()+expiredays);
[Link]=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+[Link]());
}

The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days
until the cookie expires.

In the function above we first convert the number of days to a valid date, then we add the number of days until the
cookie should expire. After that we store the cookie name, cookie value and the expiration date in the
[Link] object.

Then, we create another function that checks if the cookie has been set:

function getCookie(c_name)
{
if ([Link]>0)
{
c_start=[Link](c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=[Link](";",c_start);
if (c_end==-1) c_end=[Link];
return unescape([Link](c_start,c_end));
}
}
return "";
}

The function above first checks if a cookie is stored at all in the [Link] object. If the [Link]
object holds some cookies, then check to see if our specific cookie is stored. If our cookie is found, then return the
value, if not - return an empty string.

Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will
display a prompt box, asking for the name of the user:

function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
{
alert('Welcome again '+username+'!');
}
else
{
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{
setCookie('username',username,365);
}
}
}

All together now:


Example
<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if ([Link]>0)
{
c_start=[Link](c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=[Link](";",c_start);
if (c_end==-1) c_end=[Link];
return unescape([Link](c_start,c_end));
}
}
return "";
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
[Link]([Link]()+expiredays);
[Link]=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+[Link]());
}

function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
{
alert('Welcome again '+username+'!');
}
else
{
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{
setCookie('username',username,365);
}
}
}
</script>
</head>

<body onload="checkCookie()">
</body>
</html>

JavaScript Form Validation

JavaScript Form Validation

JavaScript can be used to validate data in HTML forms before sending off the content to a server.

Form data that typically are checked by a JavaScript could be:


• has the user left required fields empty?
• has the user entered a valid e-mail address?
• has the user entered a valid date?
• has the user entered text in a numeric field?

Required Fields

The function below checks if a required field has been left empty. If the required field is blank, an alert box alerts a
message and the function returns false. If a value is entered, the function returns true (means that data is OK):

function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}

The entire script, with the HTML form could look something like this:

<html>
<head>
<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}

function validate_form(thisform)
{
with (thisform)
{
if (validate_required(email,"Email must be filled out!")==false)
{[Link]();return false;}
}
}
</script>
</head>

<body>
<form action="[Link]" onsubmit="return validate_form(this)" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>

</html>

E-mail Validation

The function below checks if the content has the general syntax of an email.

This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first
character of the email address, and the last dot must at least be one character after the @ sign:

function validate_email(field,alerttxt)
{
with (field)
{
apos=[Link]("@");
dotpos=[Link](".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}

The entire script, with the HTML form could look something like this:

<html>
<head>
<script type="text/javascript">
function validate_email(field,alerttxt)
{
with (field)
{
apos=[Link]("@");
dotpos=[Link](".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}

function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address!")==false)
{[Link]();return false;}
}
}
</script>
</head>

<body>
<form action="[Link]" onsubmit="return validate_form(this);" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit">
</form>
</body>

</html>

JavaScript Animation

With JavaScript we can create animated images.

JavaScript Animation

It is possible to use JavaScript to create animated images.

The trick is to let a JavaScript change between different images on different events.

In the following example we will add an image that should act as a link button on a web page. We will then add an
onMouseOver event and an onMouseOut event that will run two JavaScript functions that will change between the
images.

The HTML Code

The HTML code looks like this:

<a href="[Link] target="_blank">


<img border="0" alt="Visit W3Schools!" src="b_pink.gif" id="b1"
onmouseOver="mouseOver()" onmouseOut="mouseOut()" /></a>

Note that we have given the image an id, to make it possible for a JavaScript to address it later.

The onMouseOver event tells the browser that once a mouse is rolled over the image, the browser should execute
a function that will replace the image with another image.

The onMouseOut event tells the browser that once a mouse is rolled away from the image, another JavaScript
function should be executed. This function will insert the original image again.

The JavaScript Code

The changing between the images is done with the following JavaScript:

<script type="text/javascript">
function mouseOver()
{
[Link]("b1").src ="b_blue.gif";
}
function mouseOut()
{
[Link]("b1").src ="b_pink.gif";
}
</script>

The function mouseOver() causes the image to shift to "b_blue.gif".


The function mouseOut() causes the image to shift to "b_pink.gif".

The Entire Code

Example
<html>
<head>
<script type="text/javascript">
function mouseOver()
{
[Link]("b1").src ="b_blue.gif";
}
function mouseOut()
{
[Link]("b1").src ="b_pink.gif";
}
</script>
</head>

<body>
<a href="[Link] target="_blank">
<img border="0" alt="Visit W3Schools!" src="b_pink.gif" id="b1"
onmouseover="mouseOver()" onmouseout="mouseOut()" /></a>
</body>
</html>

JavaScript Image Maps

An image-map is an image with clickable regions.

HTML Image Maps

From our HTML tutorial we have learned that an image-map is an image with clickable regions. Normally, each
region has an associated hyperlink. Clicking on one of the regions takes you to the associated link. Look at our
simple HTML image-map.

Adding some JavaScript

We can add events (that can call a JavaScript) to the <area> tags inside the image map. The <area> tag supports
the onClick, onDblClick, onMouseDown, onMouseUp, onMouseOver, onMouseMove, onMouseOut, onKeyPress,
onKeyDown, onKeyUp, onFocus, and onBlur events.

Here's the HTML image-map example, with some JavaScript added:


Example
<html>
<head>
<script type="text/javascript">
function writeText(txt)
{
[Link]("desc").innerHTML=txt;
}
</script>
</head>

<body>
<img src="[Link]" width="145" height="126"
alt="Planets" usemap="#planetmap" />

<map name="planetmap">
<area shape ="rect" coords ="0,0,82,126"
onMouseOver="writeText('The Sun and the gas giant planets like Jupiter
are by far the largest objects in our Solar System.')"
href ="[Link]" target ="_blank" alt="Sun" />

<area shape ="circle" coords ="90,58,3"


onMouseOver="writeText('The planet Mercury is very difficult to study
from the Earth because it is always so close to the Sun.')"
href ="[Link]" target ="_blank" alt="Mercury" />

<area shape ="circle" coords ="124,58,8"


onMouseOver="writeText('Until the 1960s, Venus was often considered a
twin sister to the Earth because Venus is the nearest planet to us, and
because the two planets seem to share many characteristics.')"
href ="[Link]" target ="_blank" alt="Venus" />
</map>

<p id="desc"></p>

</body>
</html>

JavaScript Timing Events

JavaScript can be executed in time-intervals.

This is called timing events.

JavaScript Timing Events

With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:

• setTimeout() - executes a code some time in the future


• clearTimeout() - cancels the setTimeout()

Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.
The setTimeout() Method

Syntax
var t=setTimeout("javascript statement",milliseconds);

The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you
want to cancel this setTimeout(), you can refer to it using the variable name.

The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a
statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()".

The second parameter indicates how many milliseconds from now you want to execute the first parameter.

Note: There are 1000 milliseconds in one second.

Example

When the button is clicked in the example below, an alert box will be displayed after 5 seconds.

Example
<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000);
}
</script>
</head>

<body>
<form>
<input type="button" value="Display timed alertbox!"
onClick="timedMsg()" />
</form>
</body>
</html>

Example - Infinite Loop

To get a timer to work in an infinite loop, we must write a function that calls itself.

In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.

Notice that we also have a function that checks if the timer is already running, to avoid creating additional timers,
if the button is pressed more than once:
Example
<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
[Link]('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

The clearTimeout() Method

Syntax
clearTimeout(setTimeout_variable)

Example

The example below is the same as the "Infinite Loop" example above. The only difference is that we have now
added a "Stop Count!" button that stops the timer:
Example
<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
[Link]('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
</body>
</html>

JavaScript Create Your Own Objects

Objects are useful to organize information.

JavaScript Objects

Earlier in this tutorial we have seen that JavaScript has several built-in objects, like String, Date, Array, and more.
In addition to these built-in objects, you can also create your own.

An object is just a special kind of data, with a collection of properties and methods.

Let's illustrate with an example: A person is an object. Properties are the values associated with the object. The
persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these properties,
but the values of those properties will differ from person to person. Objects also have methods. Methods are the
actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.
Properties

The syntax for accessing a property of an object is:

[Link]

You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can
give it properties named firstname, lastname, age, and eyecolor as follows:

[Link]="John";
[Link]="Doe";
[Link]=30;
[Link]="blue";

[Link]([Link]);

The code above will generate the following output:

John

Methods

An object can also contain methods.

You can call a method with the following syntax:

[Link]()

Note: Parameters required for the method can be passed between the parentheses.

To call a method called sleep() for the personObj:

[Link]();

Creating Your Own Objects

There are different ways to create a new object:

1. Create a direct instance of an object

The following code creates an instance of an object and adds four properties to it:

personObj=new Object();
[Link]="John";
[Link]="Doe";
[Link]=50;
[Link]="blue";
Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj:

[Link]=eat;

2. Create a template of an object

The template defines the structure of an object:

function person(firstname,lastname,age,eyecolor)
{
[Link]=firstname;
[Link]=lastname;
[Link]=age;
[Link]=eyecolor;
}

Notice that the template is just a function. Inside the function you need to assign things to [Link]. The
reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're
dealing with must be clear). That's what "this" is: the instance of the object at hand.

Once you have the template, you can create new instances of the object, like this:

myFather=new person("John","Doe",50,"blue"); myMother=new person("Sally","Rally",48,"green");

You can also add some methods to the person object. This is also done inside the template:

function person(firstname,lastname,age,eyecolor)
{
[Link]=firstname;
[Link]=lastname;
[Link]=age;
[Link]=eyecolor;

[Link]=newlastname;
}

Note that methods are just functions attached to objects. Then we will have to write the newlastname() function:

function newlastname(new_lastname)
{
[Link]=new_lastname;
}

The newlastname() function defines the person's new last name and assigns that to the person. JavaScript knows
which person you're talking about by using "this.". So, now you can write: [Link]("Doe").

JavaScript Summary

This tutorial has taught you how to add JavaScript to your HTML pages, to make your web site more dynamic and
interactive.
You have learned how to create responses to events, validate forms and how to make different scripts run in
response to different scenarios.

You have also learned how to create and use objects, and how to use JavaScript's built-in objects

Now You Know JavaScript, What's Next?

The next step is to learn about the HTML DOM and DHTML.

If you want to learn about server-side scripting, the next step is to learn ASP.

HTML DOM

The HTML DOM defines a standard way for accessing and manipulating HTML documents.

The HTML DOM is platform and language independent and can be used by any programming language like Java,
JavaScript, and VBScript.

DHTML

DHTML is a combination of HTML, CSS, and JavaScript. DHTML is used to create dynamic and interactive Web sites.

W3C once said: "Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets
and scripts that allows documents to be animated."

ASP

While scripts in an HTML file are executed on the client (in the browser), scripts in an ASP file are executed on the
server.

With ASP you can dynamically edit, change or add any content of a Web page, respond to data submitted from
HTML forms, access any data or databases and return the results to a browser, customize a Web page to make it
more useful for individual users.

Common questions

Powered by AI

In JavaScript, regular expressions (RegExp) are used to describe patterns for matching text. They provide robust functionality for searching, parsing, and editing strings through pattern matching. Defined using syntax like 'new RegExp(pattern, modifiers)' or simply '/pattern/modifiers', regular expressions help perform complex search-and-replace operations . Modifiers such as 'g' for global search, 'i' for case-insensitivity, and 'm' for multiline search enhance the flexibility of patterns . Common applications include validating input data formats (e.g., emails, dates), finding substrings within larger text, and replacing patterns in strings. For instance, input validation can be performed by ensuring that an email input contains an "@" and a dot in the correct positions, aided by regular expressions . Thus, RegExp plays an essential role in text processing and data validation tasks within JavaScript, offering efficient and concise solutions for complex string manipulations .

The JavaScript Date object can be instantiated in multiple ways, each serving specific use cases in date and time handling. The simplest instantiation is 'new Date()', which creates a Date object initialized to the current date and time . Using 'new Date(milliseconds)' creates a Date object based on the number of milliseconds elapsed since January 1, 1970, offering precision for temporal calculations . 'new Date(dateString)' parses a string representation of a date and time, useful for applications that handle string-based date input . Lastly, 'new Date(year, month, day, etc.)' allows detailed date and time construction by specifying individual components, providing granular control as needed . These methods underscore JavaScript's versatility in handling diverse temporal data representations, crucial in applications involving scheduling, logging events, or time-stamping activities . Each instantiation method caters to specific data formats or requirements, offering flexibility and adaptability in web development .

In JavaScript, properties are the values associated with an object, while methods are the actions that can be performed on objects. For instance, within the String object, 'length' is a property that gives the number of characters in a string as in 'txt.length' where 'txt' is the string variable . In contrast, 'toUpperCase()' is a method that converts all characters of a string to uppercase, such as 'str.toUpperCase()' resulting in an output of 'HELLO WORLD!' for 'str = "Hello world!"' . Similarly, for the Date object, creation of a date through 'new Date()' incorporates properties like year, month, day, etc., that can be accessed or modified through methods like 'setFullYear()' . Thus, while properties represent object data, methods encapsulate actions or operations that modify or interact with this data .

JavaScript offers strategies to validate form data for ensuring accuracy and completeness before submission. Critical validation checks include verifying required fields are not blank, ensuring email addresses conform to proper syntax, and confirming that dates are valid and formatted correctly . For instance, the 'validate_required()' function can be employed to alert users when a required field is left empty . Similarly, 'validate_email()' checks whether an input has an '@' symbol and a dot following certain rules . These strategies are vital to ensure data integrity and usability once received by the server. Pre-submission validation helps prevent user errors, mitigates server processing failures, and enhances user experience by providing immediate feedback . Validating on the client-side reduces server load by filtering out improperly formatted data, emphasizing its importance in efficient web application architecture .

JavaScript animations enhance user interaction on web pages by creating dynamic and engaging visual effects. By changing image attributes in response to user actions, such as mouse movements during events like onMouseOver and onMouseOut, animations can make a page more interactive and visually appealing . For instance, a button could change color when hovered over, signaling interactivity to the user . However, potential pitfalls include performance issues on less powerful devices when animations are not optimized, potential accessibility concerns if visual changes are not accompanied by alternative text or cues, and creating distractions that hinder task completion or user experience . To mitigate these, developers should ensure animations complement the content and purpose, are performance-optimized, do not interfere with accessibility standards, and include options to disable animations for users who prefer a static interface.

JavaScript's Array object is pivotal for managing collections of data by providing a structured way to store multiple values under a single variable name. Arrays allow for efficient data handling, access, and manipulation. For instance, arrays can be created via multiple syntaxes such as 'new Array()' or using array literals like '["Saab", "Volvo", "BMW"]', which allow storing strings, numbers, or booleans . Arrays support index-based access, where indices start at 0, making operations like iteration straightforward; accessing the first element can be done with 'array[0]' . Additionally, arrays offer dynamic sizing and a suite of methods for robust operations including adding, removing, or sorting elements. The Array object is instrumental in handling lists of data, supporting loops, and enabling complex data transformations, making it indispensable for both simple tasks and complex data-driven applications in JavaScript .

JavaScript's Boolean object converts non-Boolean values to Boolean 'true' or 'false'. The object returns 'false' if the initial value is 0, -0, null, '', false, undefined, or NaN; otherwise, it returns 'true', even for strings that are non-empty, such as "false" . For instance, 'new Boolean(0)' or 'new Boolean(null)' will yield false, whereas 'new Boolean("true")' or 'new Boolean("false")' will evaluate to true . This has critical implications in logic operations where implicit type conversion is prevalent. It ensures that any non-zero value or non-empty string is inherently truthy, which may lead to logical errors if developers assume "false" (as a string) equates to a Boolean false . Understanding these nuances is crucial for writing predictable and bug-free conditional statements in JavaScript applications.

JavaScript's Math object provides a comprehensive suite of constants and methods crucial for mathematical computations in web applications. Constants such as Math.PI, Math.E, and others represent frequently used mathematical values . For example, Math.PI can be used to calculate the circumference of a circle using the formula '2 * Math.PI * radius'. In addition to constants, methods like Math.sqrt(), Math.round(), Math.random(), and Math.floor() offer functionality for square root calculation, rounding numbers, generating random values, and flooring decimal numbers, respectively . These tools are essential for creating dynamic visualizations, performing scientific calculations, or controlling animations in web interfaces. The Math object excels in situations requiring precision and varied mathematical operations without the need for additional libraries, thereby enhancing the robustness of JavaScript-based computations .

JavaScript cookies play a crucial role in session management by storing small pieces of data on the user's device to retain information across sessions. Functions like 'setCookie()' and 'getCookie()' are utilized to save and access data like user preferences or login sessions . For example, a website might store a username in a cookie using 'setCookie()' to personalize content on future visits . Cookies thus facilitate user-specific settings, tracking user behavior, and maintaining session state across different pages or revisits. While their utility is significant in enhancing user experience, it's important to manage cookies with consideration of privacy regulations and provide options for users to review or disable cookies as necessary to comply with data protection standards . Cookies, being limited in size and scope, are supplemented by other mechanisms like localStorage or sessionStorage for more extensive data management tasks.

JavaScript's 'setTimeout' and 'clearTimeout' functions are used to control timing events. 'setTimeout' schedules a function to execute after a specified number of milliseconds, thereby allowing developers to delay code execution . For example, 'setTimeout("alert('5 seconds!')", 5000)' triggers an alert after 5 seconds . Alternatively, 'clearTimeout' cancels the timeout if it’s no longer necessary, preventing the scheduled function call . In web development, these functions are crucial for asynchronous tasks, such as delaying UI updates, creating animations, or managing intervals without blocking the main execution thread, thus enhancing user experience by avoiding abrupt operations .

You might also like