Site icon i2tutorials

Javascript-Object

Javascript-Object

 

A JavaScript object is an entity having state and behavior (real-life properties and method). Example: In real life, a car, pen, bike, chair, glass, keyboard, monitor, etc., is an object.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class-based. Here, we do not create a class to get the object. But, we direct create objects.

 

Creating Objects in JavaScript:

 

3 ways to create objects.

⦁  By object literal

⦁  By creating an instance of Object directly (using the new keyword)

⦁   By using an object constructor (using the new keyword)

 

syntax:

 

object={property1:value1,property2:value2.....propertyN:valueN}

 

Example:

 

<html>
<body>
<script> 
emp={id:102,name:"student",salary:40000} 
document.write(emp.id+" "+emp.name+" "+emp.salary); 
</script>
</body>
</html>

 

OUTPUT:

 

102 student 40000

 

By creating instance of Object:

 

syntax:

 

var objectname=new Object();

 

new keyword is used to create object.

 

Example:

 

<html>
<body>
<script> 
var emp=new Object(); 
emp.id=101; 
emp.name="Ravi"; 
emp.salary=50000; 
document.write(emp.id+" "+emp.name+" "+emp.salary); 
</script>
</body>
</html>

 

OUTPUT:

 

101 Ravi 50000

 

By using an Object constructor:

 

this keyword refers to the current object.

 

Example:

 

<html>
<body>
<script> 
function emp(id,name,salary){ 
this.id=id; 
this.name=name; 
this.salary=salary; 
} 
e=new emp(103,"Vimal",30000); 

document.write(e.id+" "+e.name+" "+e.salary); 
</script> 
</body>
</html>

 

OUTPUT:

 

103 Vimal 30000

 

Defining method:

 

We can define a method in a JavaScript object. But before defining the method, we need to add a property in the function with the same name as a method.

 

Example:

 

<html>
<body>
<script> 
function emp(id,name,salary){ 
this.id=id; 
this.name=name; 
this.salary=salary; 

this.changeSalary=changeSalary; 
function changeSalary(otherSalary){ 
this.salary=otherSalary; 
} 
} 
e=new emp(103,"Student1",30000); 
document.write(e.id+" "+e.name+" "+e.salary); 
e.changeSalary(45000); 
document.write("<br>"+e.id+" "+e.name+" "+e.salary); 
</script> 
</body>
</html>

 

OUTPUT:

 

103 Student1 30000

103 Student1 45000

 

JavaScript Object Methods:

 

 

Exit mobile version