USER DEFINED OBJECTS IN JAVASCRIPT - PAGE(2)

next>>

Defining Methods for an Object:

we need to complete the definition of an object by assigning methods to it.

Example:

to show how to add a function along with an object:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
 
// Define a function which will work as a method
function addPrice(amount){
    this.price = amount; 
}
 
function book(title, author){
    this.title = title; 
    this.author  = author;
    this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Programming in C", "Balagurusamy");
   myBook.addPrice(200);
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
   document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

The with Keyword:

·         The with keyword is used as a kind of shorthand for referencing an object's properties or methods.
·         The object specified as an argument to with becomes the default object for the duration of the block that follows.
·         The properties and methods for the object can be used without naming the object.

Syntax:

with (object){
    properties used without the object name and dot
}

Example:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
 
// Define a function which will work as a method
function addPrice(amount){
    with(this){
       price = amount; 
    }
}
function book(title, author){
    this.title = title; 
    this.author  = author;
    this.price = 0;
    this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Programming in C", "Balagurusamy");
   myBook.addPrice(100);
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
   document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
next>>



No comments:

Post a Comment