JavaScript Lesson 33: Creating an Object Using Literal Notation

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

<Previous Lesson> [Table of Contents] <Next Lesson>

Introduction

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.

Creating an Object

There are two ways to create a JavaScript object, namely using literal notation and using object constructor notation

1. Using Literal Notation

The syntax to create an object is

var objectName={

property1="=value1,
property2="=value2,
..................
.................
proeprtyn=valuen,
MyMethod: MyFunction(){ }

};

Example 1.1

<!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 output

The Phone Object.

Model:

Brand:

Price:

 

The following example comprises a function:

Example 1.2

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.

 

The output

Student Name:

BMI :





<Previous Lesson> [Table of Contents] <Next Lesson>

“>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone