Web Design and
development
Lecture 9
Course Instructor: Wardah Mahmood
Email Id: [Link]@[Link]
JavaScript Objects
JavaScript Objects
• In JavaScript, almost "everything" is an object.
• Booleans can be objects (if defined with the new keyword)
• Numbers can be objects (if defined with the new keyword)
• Strings can be objects (if defined with the new keyword)
• Dates are always objects
• Maths are always objects
• Regular expressions are always objects
• Arrays are always objects
• Functions are always objects
• Objects are always objects
• All JavaScript values, except primitives, are objects.
JavaScript Objects
• There are two basic ways to create an empty object:
Using constructor
var obj = new Object();
and, the second is called object literal syntax, and is more convenient. This syntax is also the
core of JSON format and should be preferred at all times.
var obj = {};
See: [Link]
JavaScript Objects (Using
Constructor)
function person(first, last, age) {
[Link] = first;
[Link] = last;
[Link] = age;
}
var p = new person("John", "Doe", 40);
[Link]="Jane";
[Link]="Doe";
[Link]=30;
JavaScript Objects (Using Literal)
var person = {
firstName:"",
lastName:"",
age:0
};
var p = new person("John", "Doe", 40);
[Link]="Jane";
[Link]="Doe";
[Link]=30;
JavaScript Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.
var person = {firstName:"John", lastName:"Doe", age:40};
var x = person;
[Link] = 10; // This will change both [Link] and [Link]
JavaScript Object Methods
function person(first, last, age) {
[Link] = first;
[Link] = last;
[Link] = age;
[Link] = function () {
return [Link] + " " + [Link];
}
}
var p = new person("John", "Doe", 40);
var fn=[Link]();
JavaScript Object Prototypes
• Every JavaScript object has a prototype.
• All JavaScript objects inherit the properties and methods from their prototype.
• Objects created using an object literal, or with new Object(), inherit from a prototype called
[Link].
• The standard way to create an object prototype is to use an object constructor
function:
function person(first, last, age) {
[Link] = first;
[Link] = last;
[Link] = age;
}
var p = new person("John", "Doe", 40);
Extending Instance
function person(first, last, age) {
[Link] = first;
[Link] = last;
[Link] = age;
}
var p = new person("John", "Doe", 40);
[Link] = "Male";
[Link] = function() {
return [Link] + " " + [Link];
};
Extending Prototype
function person(first, last, age) {
[Link] = first;
[Link] = last;
[Link] = age;
}
var p = new person("John", "Doe", 40);
[Link] = "Male";
[Link] = function() {
return [Link] + " " + [Link];
};
Inheritance Using Prototype
function parentClass() {
this.parentProperty1 = "A";
this.parentMethod1 = function(arg1) {
return "Parent Method 1: " + arg1; };
}
function childClass() {
this.childProperty1 = "B";
this.childMethod1 = function(arg1) {
return "Child Method 1: " + arg1; };
}
[Link]=new parentClass();
var c=new childClass();
[Link] ("Child Property: "+c.childProperty1);
[Link] ("Parent Property: "+c.parentProperty1);
[Link] (c.childMethod1("By Child Instance"));
[Link] (c.parentMethod1("By Child Instance"));
Overloading Parent Method
function parentClass() {
this.parentProperty1 = "A";
this.parentMethod1 = function(arg1) {
return "Parent Method 1: " + arg1; };
}
function childClass() {
this.childProperty1 = "B";
this.childMethod1 = function(arg1) {
return "Child Method 1: " + arg1; };
}
[Link]=new parentClass();
[Link].parentMethod1 = function(arg1) {
return "Overloaded Parent Method 1: " + arg1; };
var c=new childClass();
[Link] ("Child Property: "+c.childProperty1);
[Link] ("Parent Property: "+c.parentProperty1);
[Link] (c.childMethod1("By Child Instance"));
[Link] (c.parentMethod1("By Child Instance"));
JavaScript BUILT in Objects
JavaScript String Object
Methods:
• charAt() Returns the character at the specified index
• substr() Extracts the characters from a string, beginning at a specified start position, and through
the specified number of character
• toLowerCase() Converts a string to lowercase letters
• toUpperCase() Converts a string to uppercase letters
Property:
• length
See: [Link]
JavaScript String Object
var txt = "Hello World!";
[Link]("Length of String:" + [Link] + "<br />");
[Link]([Link]() + "<br />");
[Link]([Link]());
See: Example 05
JavaScript String Object
Escape sequences behave as in Java
\' \" \& \n \t \\
For Example:
str="We can have \"double quotes\" in strings";
[Link](str + "<br />");
See: Example 07
JavaScript Array Object
Three ways to initialize an array in JavaScript:
var stooges = new Array();
stooges[0] = "Larry";
stooges[1] = "Moe";
stooges[2] = "Curly";
var stooges = new Array("Larry", "Moe", "Curly");
var stooges = ["Larry", "Moe", "Curly"];
JavaScript Array Object
Methods:
• concat() Joins two or more arrays, and returns a copy of the joined arrays
• join() Joins all elements of an array into a string
• reverse() Reverses the order of the elements in an array
• slice() Selects a part of an array, and returns the new array
• sort() Sorts the elements of an array
• toString() Converts an array to a string, and returns the result
The “arguments” Array
• Every function contains an array named arguments representing the parameters passed
• Can loop over them, print/alert them, etc.
• Allows you to write functions that take varying numbers of parameters
function example() {
for (var i = 0; i < [Link]; i++)
{
alert(arguments[i]);
}
}
example("how", "are", "you");
See: Example 01
Arrays as Maps
• The index of a JS array need not be integers!
• This allows you to store mappings between an index of any type ("keys") and value
• Similar to Java's Map collection or a hash table data structure
var map = new Array();
map[42] = "the answer";
map[3.14] = "pi";
map["champ"] = "FC";
See: Example 02
The For...In Loop
Loops over every index of the array, or every property name of the object
var map = new Array();
map[42] = "the answer";
map[3.14] = "pi";
map["champ"] = "suns";
for (var x in map) {
[Link](x + "<br />");
}
See: Example 03
JavaScript Date Object
Four ways of instantiating a date:
var today = new Date();
// milliseconds since 1970/01/01
var d1 = new Date(1000000);
// date string
var d2 = new Date("October 17, 1979 [Link]");
// year, month, day, hours, minutes, seconds, milliseconds
var d3 = new Date(79,9,17,11,33,0);
JavaScript Date Object
Methods:
• getDate() Returns the day of the month (from 1-31)
• getDay() Returns the day of the week (from 0-6)
• getFullYear() Returns the year (four digits)
• getHours() Returns the hour (from 0-23)
• getMilliseconds() Returns the milliseconds (from 0-999)
• getMinutes() Returns the minutes (from 0-59)
• getMonth() Returns the month (from 0-11)
• getSeconds() Returns the seconds (from 0-59)
• getTime() Returns the number of milliseconds since midnight Jan 1, 1970
JavaScript Date Object
var currentDate = new Date();
var month = [Link]() + 1;
var day = [Link]();
var year = [Link]();
[Link](currentDate + "<br />");
[Link](month + "/" + day + "/" + year);
See: Example 04 Example 08 (Difference)
JavaScript Math Object
• The Math object allows you to perform mathematical tasks.
var x = [Link];
var y = [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.
JavaScript Math Object
Methods:
• abs(x) Returns the absolute value of x
• ceil(x) Returns x, rounded upwards to the nearest
• floor(x) Returns x, rounded downwards to the nearest integer
• max(x,y,z,...,n) Returns the number with the highest value
• min(x,y,z,...,n) Returns the number with the lowest value
• random() Returns a random number between 0 and 1
• round(x) Rounds x to the nearest integer
See: [Link]
JavaScript Math Object
x=[Link]();
// random number between 0 and 1
[Link](x + "<br />");
x=[Link](x*11);
// random integer between 0 and 10
[Link](x + "<br />");
See: Example 06
JavaScript RegExp Object
• RegExp, is short for regular expression.
• A regular expression is an object that describes a pattern of characters.
• Regular expressions are used to perform powerful pattern-matching and "search-and-replace"
functions on text.
var patt=new RegExp(pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;
• Pattern specifies the pattern of an expression
• Modifiers specify if a search should be global, case-sensitive, etc.
See: [Link]
JavaScript RegExp Object
Example 1
Do a case-insensitive search for "w3schools" in a string:
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
[Link]([Link](patt1));
JavaScript RegExp Object
Example 2
Perform a global, case-insensitive search (the word Microsoft will be replaced each
time it is found):
var str="Welcome to Microsoft! ";
str=str + "We are proud to announce that Microsoft has ";
str=str + "one of the largest Web Developers sites in the world.";
[Link]([Link](/microsoft/gi, "W3Schools"));
JavaScript RegExp Object
RegExp test() Method
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":
var patt1=new RegExp("e");
[Link]([Link]("The best things in life are free"));
JavaScript RegExp Object
RegExp exec() Method
The exec() method searches a string for a specified value, and returns the first
match. If no match is found, it returns null. The following example searches a string
for the character "e":
var patt1=new RegExp("e");
[Link]([Link]("The best things in life are free"));
JavaScript RegExp Object
Validate Email Address
Validate email address using JavaScript regular expression:
function validateEmail(elementValue)
{
var emailPattern;
emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return [Link](elementValue);
}
if (validateEmail("user@[Link]"))
{ [Link]("Valid Email"); }
else
{ [Link]("Invalid Email"); }
See: Example 09 See: [Link]