Creating Objects in Javascript

JavaScript coding is all about objects. This articles will guide you through creating objects in JavaScript. In JavaScript there are two ways you can define an Object.

Direct Instance of Object:
In this technique you create the object using “new” operator.





Example - Direct Instance of Object

<script type="text/javascript">
  var employeeObj = new Object();
  employeeObj.firstname="Jim";
  employeeObj.lastname="John";
  employeeObj.age=50;
  employeeObj.eyecolor="blue";
</script>

Explanation: Here i am creating object instance employeeObj having 4 properties firstname, lastname, age and eyecolor.

Template of Object
In this technique the object defines the structure where the object will only accept predefined list of arguments.
Example - Template of Object

<script type="text/javascript">
function person(firstname,lastname,age,eyecolor)
{
   this.firstname=firstname
   this.lastname=lastname
   this.age=age
   this.eyecolor=eyecolor
}
employeeObj=new person("Jim","John",50,"blue")
employeeObj1=new person("Sally","Rally",48,"green")
</script>

Explanation: Here i have defined the function for the Object and creating new instance of the object using new operator.

Similar Posts

Custom Search

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)