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!";
document.write(txt.length);
</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!";
document.write(str.toUpperCase());
</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!";
document.write(txt.length);
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!";
document.write(txt.toUpperCase());
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 00:00:00 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 11:13:00")
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();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+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();
myDate.setFullYear(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:
document.write(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:
document.write(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=Math.PI;
var sqrt_value=Math.sqrt(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
Math.PI
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:
document.write(Math.round(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:
document.write(Math.random());
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:
document.write(Math.floor(Math.random()*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");
document.write(patt1.test("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");
document.write(patt1.exec("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">
document.write("Browser CodeName: " + navigator.appCodeName);
document.write("<br /><br />");
document.write("Browser Name: " + navigator.appName);
document.write("<br /><br />");
document.write("Browser Version: " + navigator.appVersion);
document.write("<br /><br />");
document.write("Cookies Enabled: " + navigator.cookieEnabled);
document.write("<br /><br />");
document.write("Platform: " + navigator.platform);
document.write("<br /><br />");
document.write("User-agent header: " + navigator.userAgent);
</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();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
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
document.cookie object.
Then, we create another function that checks if the cookie has been set:
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
The function above first checks if a cookie is stored at all in the document.cookie object. If the document.cookie
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 (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
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)
{email.focus();return false;}
}
}
</script>
</head>
<body>
<form action="submit.htm" 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=value.indexOf("@");
dotpos=value.lastIndexOf(".");
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=value.indexOf("@");
dotpos=value.lastIndexOf(".");
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)
{email.focus();return false;}
}
}
</script>
</head>
<body>
<form action="submit.htm" 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="http://www.w3schools.com" 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()
{
document.getElementById("b1").src ="b_blue.gif";
}
function mouseOut()
{
document.getElementById("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()
{
document.getElementById("b1").src ="b_blue.gif";
}
function mouseOut()
{
document.getElementById("b1").src ="b_pink.gif";
}
</script>
</head>
<body>
<a href="http://www.w3schools.com" 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)
{
document.getElementById("desc").innerHTML=txt;
}
</script>
</head>
<body>
<img src="planets.gif" 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 ="sun.htm" 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 ="mercur.htm" 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 ="venus.htm" 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()
{
document.getElementById('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()
{
document.getElementById('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:
objName.propName
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:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";
document.write(personObj.firstname);
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:
objName.methodName()
Note: Parameters required for the method can be passed between the parentheses.
To call a method called sleep() for the personObj:
personObj.sleep();
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();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj:
personObj.eat=eat;
2. Create a template of an object
The template defines the structure of an object:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
Notice that the template is just a function. Inside the function you need to assign things to this.propertyName. 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)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.newlastname=newlastname;
}
Note that methods are just functions attached to objects. Then we will have to write the newlastname() function:
function newlastname(new_lastname)
{
this.lastname=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: myMother.newlastname("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.