The previous examples demonstrates how the constructor create the object and assign properties. But we need to complete the definition of an object by assigning method to it.
Example:
Here is a simple 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.subject = "title";
this.author = "author";
this.addPrice = addPrice; //Assign that method as property
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is: " +myBook.title+ "<br>");
document.write("Book author is: " +myBook.author+ "<br>");
document.write("Book author 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
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("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is: " +myBook.title+ "<br>");
document.write("Book author is: " +myBook.author+ "<br>");
document.write("Book author is: " +myBook.price+ "<br>");
</script>
</body>
</html>
0 comments:
Post a Comment