An object is something that has properties and methods. For example, a car has properties like color, model, and methods such as start, accelerate and stop.
An object in JavaScript also has properties and methods. A JavaScript object actually comprises variables and functions. A variable inside an object is called a property and a function inside an object is called a method.
There are two ways to create a JavaScript object, namely using literal notation and using object constructor notation
The syntax to create an object is
var objectName={ property1="=value1, property2="=value2, .................. ................. proeprtyn=valuen, MyMethod: MyFunction(){ } };
<!DOCTYPE html> <html> <body> <p>The Phone Object.</p> <h3>Model:<b id="model"></b></h3> <h3> Brand:<b id="brand"></b></h3> <h3>Price:<b id="price"></b></h3> <script> var phone= {model:"Note8", brand:"Samsung", color:"white",price:"$2000"}; document.getElementById("model").innerHTML = phone.model; document.getElementById("brand").innerHTML = phone.brand; document.getElementById("price").innerHTML = phone.price; </script> </body> </html>
The Phone Object.
The following example comprises a function:
var student={ name:'George', height:1.78, weight:75, bmi: function(){ var x=this.weight/Math.pow(this.height,2); var y=x.toFixed(2); return y; } }; var student_Name=document.getElementById('studentname'); student_Name.textContent=student.name; var student_bmi=document.getElementById('bmi_index'); student_bmi.textContent=student.bmi();
The object is student that comprise properties name, height, and weight. Its method is bmi that calculates the bmi index of a particular student. Notice that each property comprises name:value pairs and must be separated by a comma.
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy