Object Based Programming

Object-Based Programming

Everything is an object in JS. A javascript object is an entity having state and behavior. Object-based languages have the inbuilt objects. E.g., JavaScript has a window object.

There are 3 ways to create objects.

  • By object literal
    The syntax of creating object using object literal is given below:
    object={property1:value1,property2:value2…..properyN:valueN}

Example:

<html>  
<body>  
<script>  
emp={id:1,name:"Anil Sharma",salary:15000}
document.write(emp.id+""emp.name+""+emp.salary);
</script>  
</body>  
</html>  

Output:  
1 Anil Sharma 15000  
  • By creating an instance of an Object directly
    The syntax of creating an object directly is given below:
    var objectname=new Object();
    Here,a new keyword is used to create an object.

Example:

<html>  
<body>  
<script>  
var emp=new Object();  
emp.id=1;
emp.name="Anil Sharma";
emp.salary=1500;
document.write(emp.id+""+emp.name+""+emp.salary);
</script>
</body>
</html> 

Output:  
Anil Sharma 15000
  • By using an object constructor
    Here, we need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.

Example:

<html>  
<body>  
<script>  
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;   
} 
e=new emp(1,"Anil Sharma",15000);
document.write(e.id+""+e.name+""+e.salary);
</script>
</body>
</html> 

Output:  
1 Anil Sharma 15000  

Event Handling

JavaScript’s interaction with HTML elements is handled through events that occur when the user or the browser manipulates a page. When the page loads, it is called an event. Examples include events like pressing any key, closing window, or resizing a window. Event handlers are the code that invokes a specific piece of code when a particular action happens on an HTML elements.