JavaScript Tutorial JavaScript Examples CSS Tutorial HTML Tutorial About Us

Lesson 34: Creating Object Part 2


We can create an object in JavaScript using the New keyword and the Object() constructor function. Bear in mind the O of the Object function must be a capital letter, otherwise it will not work.

After creating the Object, you can then add properties and method to it using the dot notation. Please ensure that each element that adds a property or method should end with a semicolon.

Example: A Car Object

The JavaScript
var car=new Object();
car.brand='Toyota';
car.model='Camry';
car.capacity='2000cc';
car.stock=10000;
car.booked=3000;
car.checkBalance=function(){
return this.stock-this.booked;
};
var carbrand=document.getElementById('carbrand');
carbrand.textContent=car.brand;
var carmodel=document.getElementById('carmodel');
carmodel.textContent=car.model;
var carbalance=document.getElementById('balance');
carbalance.textContent=car.checkBalance();

In this example, checkBalance is a method, it is actually a function by itself.

The corresponding HTML document

<!DOCTYPE html>
<html>
<body>
<h1>Car brand:<b id="carbrand"></b></h1>
<h1>Car Model:<b id="carmodel"></b></h1>
<h2>Number of Cars Left:<b id="balance"></b></h2>
<script type="text/javascript" src="car.js"></script>

</body>
</html>
The Output

Car brand:

Car Model:

Number of Cars Left:


❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy