Objects Objects are just a way of representing data. They provide a way to organize a collection of...

26
Objects • Objects are just a way of representing data. They provide a way to organize a collection of data into a single unit. • If objects are nouns, adjectives are their properties and verbs are their methods. Types of objects - User defined objects. - Core or built-in objects (Date, String, Number) - Browser and Document objects.

Transcript of Objects Objects are just a way of representing data. They provide a way to organize a collection of...

Objects

• Objects are just a way of representing data. They provide a way to organize a collection of data into a single unit.

• If objects are nouns, adjectives are their properties and verbs are their methods.

Types of objects

- User defined objects.

- Core or built-in objects (Date, String, Number)

- Browser and Document objects.

Dot SyntaxA dot is used to separate the objects when

descending the hierarchical tree-like structure used to describe all of the components of an object.

ConstructorA constructor is a method that creates an

instance of an object. JavaScript comes with several built-in constructors. The new keyword precedes the name of the constructor that will be used to create the object. Examples of constructors: Object(), Array(), Date().

Object()The Object() constructor returns a reference to an object. The

return value is assigned to a variable.

Example<html>

<head><title>The Object() Constructor</title><script language = "javascript"> var pet = new Object(); alert(pet);</script></head>

</body></body>

</html>

Properties of the ObjectAny object subordinate to another object is also a property of that object. The properties

assigned to the object are not variables and are not defined with the var keyword.

Example<html>

<head><title>The Object() Constructor</title><script language = "javascript"> var pet = new Object(); alert(pet); pet.cat = new Object(); alert(pet.cat); pet.cat.name = "Sneaky"; pet.cat.color = "yellow"; pet.cat.size = "fat"; pet.cat.attitude = "stuckup";</script></head>

</body></body>

</html>

Methods of the Object

Methods are special functions that are used to describe how object behaves or acts:

• pet.cat.play(); // no parameters

• pet.dog.fetch(ball); // passing parameters

Format

var myobj = new Object();

Example<html>

<head><title>User-defined objects</title> <script language = "javascript"> var toy = new Object(); // Create the object toy.name = "Lego"; // Assign properties to the object toy.color = "red"; toy.shape = "rectangle"; </script></head>

<body bgcolor="lightblue"> <script language = "javascript"> document.write("<b>The toy is a " + toy.name + "."); document.write("<br>It is a " + toy.color + " " + toy.shape+ "."); </script></body>

</html>

Creating an Object with a User-Defined Function

You can create a function that specifies the object’s name, properties, and methods.

The function serves as a template or prototype of an object.

The this keyword is used to refer to the object that has been passed to a function.

Example<html>

<head><title>User-defined objects</title></head><script language = "javascript">

function book(title, author, publisher){// Defining properties this.title = title; this.author = author;

this.publisher = publisher;}

</script>

<body bgcolor="lightblue"></body><script language = "javascript">

var myBook = new book("JavaScript by Example", "Ellie", "Prentice Hall");document.writeln("<b>" + myBook.title + "<br>" + myBook.author + "<br>" + myBook.publisher);

</script></body>

</html>

Defining methods for an Object<html>

<head><title>Simple Methods</title><script language = "javascript"> function distance(r, t){ // define the object

this.rate = r; // assign propertiesthis.time = t;

} function calc_distance(){ // define a function that will be used as a method

return this.rate * this.time; }</script></head>

<body bgcolor="lightblue"><script language="javascript"> var speed=eval(prompt("What was your speed (miles per hour)? ","")); var elapsed=eval(prompt("How long did the trip take (hours)?" ,"")); var howfar=new distance(speed, elapsed); // call the constructor howfar.distance=calc_distance; // create a new property var d = howfar.distance(); // invoke method alert("The distance is " + d + " miles.");</script></body>

</html>

A Method defined in a constructor<html><head><title>User-defined objects</title><script language = "javascript"> function book(title, author, publisher){ // Receiving parameters

this.pagenumber=0; // Propertiesthis.title = title;this.author = author;this.publisher = publisher;this.uppage = pageForward; // Assign function name to a propertythis.backpage = pageBackward;

} function pageForward(){ // Functions to be used as methods

this.pagenumber++;return this.pagenumber;

} function pageBackward(){

this.pagenumber--;return this.pagenumber;

}</script></head>

A Method defined in a constructor (continued)<body bgcolor="lightblue"><script language = "javascript"> var myBook = new book("JavaScript by Example", "Ellie", "Prentice

Hall" ); //Create new object myBook.pagenumber=5; document.write( "<b>"+ myBook.title + "<br>" + myBook.author + "<br>" +

myBook.publisher + "<br>Current page is " + myBook.pagenumber ); document.write("<br>Page forward: " ); for(i=0;i<3;i++){

document.write("<br>" + myBook.uppage()); // Move forward a page } document.write("<br>Page backward: "); for(;i>0; i--){

document.write("<br>" + myBook.backpage()); // Move back a page }</script></body>

</html>

Properties can be objects<html>

<head><title>Properties Can be Objects</title><script language = "javascript">

var pet = new Object(); // pet is an objectpet.cat = new Object(); // cat is a property of the pet; object.cat is also an objectpet.cat.name="Sylvester"; // cat is assigned propertiespet.cat.color="black";pet.dog = new Object();pet.dog.breed = "Shepherd";pet.dog.name = "Lassie";

</script></head>

<body bgcolor="lightblue"><script language = "javascript">

document.write("<b>The cat's name is " + pet.cat.name + ".");document.write("<br>The dog's name is " + pet.dog.name + ".");

</script></body>

</html>

Object Literals

• Object created by assigning it a comma-separated list of properties enclosed in curly braces.

FORMAT• var object = {property1: value, property2: value};

Example<html>

<head><title>Object Literals</title></head>

<body bgcolor="yellow"><script language = "javascript">

var car = {make: "Honda",year: 2002,price: 30000,owner: "Henry Lee"};

var details=car.make + "<br>";details += car.year + "<br>";details += car.price + "<br>";details += car.owner + "<br>";document.write(details);

</script></body>

</html>

With keywordThe with keyword is used for referencing an object’s properties or methods

Example<html><head><title>The with Keyword</title><script language = "javascript">

function book(title, author, publisher){this.title = title; // propertiesthis.author = author;this.publisher = publisher;this.show = display; // Define a method

}function display(anybook){

with(this){ // The with keywordvar info = "The title is " + title;info += "\nThe author is " + author;info += "\nThe publisher is " + publisher;alert(info);

}}

</script></head>

Example (continued)<body bgcolor="lightblue">

<script language = "javascript">

var childbook = new book("A Child's Garden of Verses",

"Robert Lewis Stevenson",

"Little Brown");

var adultbook = new book("War and Peace",

"Leo Tolstoy",

"Penguin Books");

childbook.show(childbook); // call method for child's book

adultbook.show(adultbook); // call method for adult’s book

</script>

</body>

</html>

The for/in loop

can be used to iterate through a list of object properties or array elements

FORMAT

for (var property_name in object){

statements

}

Example<html><head><title>User-defined objects</title>

<script language = "javascript">function book(title, author, publisher){

this.title = title;this.author = author;this.publisher = publisher;this.show=showProps; // define a method for the object

}function showProps(obj, name){ // function to show the object's properties var result = ""; for (var prop in obj){

result += name + "." + prop + " = " +obj[prop] + "<br>";

}return result;

}</script>

</head><body bgcolor="lightblue">

<script language="javascript">myBook = new book("JavaScript by Example", "Ellie",

"Prentice Hall");document.write("<br><b>" + myBook.show(myBook, "myBook"));

</script></body></html>

prototypesOO languages support a feature called

inheritance, where an object can inherit the properties of another.

You can add properties to objects after they have been created by using the prototype objects.

In OO, the object’s data describes the properties. The object, along with its properties and methods, is bundled up into a container called a class. Each JavaScript class has a prototype object and one set of properties.

Example<html><head><title>User-defined objects and Inheritance</title>

<script language = "javascript">function Book(title, author, publisher){ // The Book class

this.title = title;this.author = author;this.publisher = publisher;this.show=showProps;

}function showProps(obj,name){

var result = "";for (var i in obj){

result += name + "." + i + " = " + obj[i] + "<br>";}return result;

}</script>

</head>

Example (continued)<body bgcolor="lightblue"><script language="javascript">// Add a new function

function lastEdition(){this.latest=prompt("Enter the latest edition for "+this.title,"");return (this.latest);

}// Add a new property with prototypeBook.prototype.edition=lastEdition;var myBook=new Book("JavaScript by Example", "Ellie", "Prentice Hall");// Define a new methoddocument.write("<br><b>" + myBook.show(myBook,"myBook")+"<br>");document.write("The latest edition is "+ myBook.edition()+"<br>");</script></body></html>

Extending a JavaScript Object

Since all objects have the prototype object, it is possible to extend the properties of a JavaScript built-in object, just as we did for a user-defined object.

Example<html><head><title>Prototypes</title><script language = "javascript"> // Customize String Functions

function uc(){var str=this.big();return( str.toUpperCase());

}function lc(){

var str=this.small();return( str.toLowerCase());

}String.prototype.bigUpper=uc;String.prototype.smallLower=lc;

var string="This Is a Test STRING.";

string=string.bigUpper();document.write(string+"<br>");document.write( string.bigUpper()+"<br>");document.write(string.smallLower()+"<br>");

</script></head><body bgcolor="lightblue"></body></html>

The Name Grabber Program• <html>• <head>• <title> Name Grabber </title>• <script>

• function copyName()• {• var userName = document.myForm.txtName.value;• var greeting = "Hi there, ";• greeting += userName;• greeting += "!";• document.myForm.txtGreeting.value = greeting;• }

• </script>• </head>

The Name Grabber Program• <body>• <center>• <h1> Name Grabber<br></h1>• <hr>

• <form name = myForm>• <table border = 1>• <tr>• <td> Please type your name: </td>• <td><input type = "text"• name = "txtName"></td>• </tr>

• <tr>• <td colspan = 2><center>• <input type = "button"• value = "click me"• onClick = 'copyName()'>• </center></td>• </tr>

• <tr>• <td colspan = 2><center>• <input type = "text"• name = "txtGreeting">• </center></td>• </tr>• </table>• </form>

• </center>• </body>• </html>

var userName = document.myForm.txtName.value;

The net result of this line is to copy the value of txtName to the userName variable.

Document.myForm.txtName.value essentially becomes a variable that you can assign values to and from, just like any other variable. Once you understand this, the following line makes perfect sense as well:

document.myForm.txtGreeting.value = greeting;