Javascript Object
An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly.
Syntax to add property to add object
objectName.objectProperty = propertyValue;
We use the write() method to document objects to write any content on the document.
Document.write("Hello world")
Example
The following example shows how to create an Object.
<!DOCTYPE html>
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Object created
book.subject = "5 points someone"; // Properties assign to the object
book.author = "ChetanBhagat";
</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>
Output
Book Name is: 5 points someone Book Author is: Chetan Bhagat
Methods of an Object
Example
<!DOCTYPE html>
<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.itle = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
varmyBook = new book("5 Points Someone", "ChetanBhagat");
myBook.addPrice(150);
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>
Output
Book Title is: 5 Points Someone Book Author is :ChetanBhagat Book Price is : 150