Web Design and
development
Lecture 9
Course Instructor: Wardah Mahmood
Email Id: [email protected]
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: http://www.w3schools.com/js/js_objects.asp
JavaScript Objects (Using
Constructor)
function person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
var p = new person("John", "Doe", 40);
p.firstName="Jane";
p.lastName="Doe";
p.age=30;
JavaScript Objects (Using Literal)
var person = {
firstName:"",
lastName:"",
age:0
};
var p = new person("John", "Doe", 40);
p.firstName="Jane";
p.lastName="Doe";
p.age=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;
x.age = 10; // This will change both x.age and person.age
JavaScript Object Methods
function person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.fullName = function () {
return this.firstName + " " + this.lastName;
}
}
var p = new person("John", "Doe", 40);
var fn=p.fullName();
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
Object.prototype.
• The standard way to create an object prototype is to use an object constructor
function:
function person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
var p = new person("John", "Doe", 40);
Extending Instance
function person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
var p = new person("John", "Doe", 40);
p.gender = "Male";
p.fullName = function() {
return this.firstName + " " + this.lastName;
};
Extending Prototype
function person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
var p = new person("John", "Doe", 40);
person.prototype.gender = "Male";
person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
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; };
}
childClass.prototype=new parentClass();
var c=new childClass();
document.write ("Child Property: "+c.childProperty1);
document.write ("Parent Property: "+c.parentProperty1);
document.write (c.childMethod1("By Child Instance"));
document.write (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; };
}
childClass.prototype=new parentClass();
childClass.prototype.parentMethod1 = function(arg1) {
return "Overloaded Parent Method 1: " + arg1; };
var c=new childClass();
document.write ("Child Property: "+c.childProperty1);
document.write ("Parent Property: "+c.parentProperty1);
document.write (c.childMethod1("By Child Instance"));
document.write (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: http://www.w3schools.com/jsref/jsref_obj_string.asp
JavaScript String Object
var txt = "Hello World!";
document.write("Length of String:" + txt.length + "<br />");
document.write(txt.toLowerCase() + "<br />");
document.write(txt.toUpperCase());
See: Example 05
JavaScript String Object
Escape sequences behave as in Java
\' \" \& \n \t \\
For Example:
str="We can have \"double quotes\" in strings";
document.write(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 < arguments.length; 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) {
document.write(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 11:13:00");
// 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 = currentDate.getMonth() + 1;
var day = currentDate.getDate();
var year = currentDate.getFullYear();
document.write(currentDate + "<br />");
document.write(month + "/" + day + "/" + year);
See: Example 04 Example 08 (Difference)
JavaScript Math Object
• The Math object allows you to perform mathematical tasks.
var x = Math.PI;
var y = 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.
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: http://www.w3schools.com/jsref/jsref_obj_math.asp
JavaScript Math Object
x=Math.random();
// random number between 0 and 1
document.write(x + "<br />");
x=Math.floor(x*11);
// random integer between 0 and 10
document.write(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: http://www.w3schools.com/js/js_obj_regexp.asp
JavaScript RegExp Object
Example 1
Do a case-insensitive search for "w3schools" in a string:
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.match(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.";
document.write(str.replace(/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");
document.write(patt1.test("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");
document.write(patt1.exec("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 emailPattern.test(elementValue);
}
if (validateEmail("[email protected]"))
{ document.write("Valid Email"); }
else
{ document.write("Invalid Email"); }
See: Example 09 See: http://www.w3schools.com/jsref/jsref_obj_regexp.asp