USER DEFINED OBJECTS-PAGE(1)

next>>

Classification of objects:

  • User Defined objects
  • Javascript native objects

User defined objects:


  • According to user needs objects can be customized by users,such objects are called as user-defined objects.
  • All user-defined objects and built-in objects are descendants of an object called Object.   
The new Operator:
·         The new operator is used to create an instance of an object.
·         To create an object, the newoperator is followed by the constructor method.

Example:

 The constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("october 17, 1947");

 The Object() Constructor:

·         A constructor is a function that creates and initializes an object.
·         JavaScript provides a special constructor function called Object() to build the object.
·         The return value of the Object() constructor is assigned to a variable.
·         The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword.

example 

demonstrates how to create an object:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object();   // Create the object
    book.subject = "programming in c"; // Assign properties to the object
    book.author  = "Balagurusamy";
</script>
</head>
<body>
<script type="text/javascript">
   document.write("Book name is : " + book.subject + "<br>");
   document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

example 

demonstrates how to create an object with a User-Defined Function. Here thiskeyword is used to refer to the object that has been passed to a function:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
    this.title = title;
    this.author  = author;
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Programming in C", "Balagurusamy");
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>


next>>

No comments:

Post a Comment