Tech Junkie Blog: JavaScript : Creating JavaScript Objects

Wednesday, March 18, 2015

JavaScript : Creating JavaScript Objects

JavaScript objects acts differently than objects in the object-oriented programming world. A JavaScript object is mutable meaning it can be changed and is dynamic.

Here is how you would create a JavaScript object:

   var Employee = new Object();
    
   Employee.ID = 1;
   Employee.FirstName = "Jeff";
   Employee.LastName = "Jordan";
You create a new object the new Object() constructor
Or you can create a JavaScript object in a literal format
   var Employee = {
      ID: 1,
      FirstName: "Jeff",
      LastName: "Jordan"
};
You can also include a function as a method in your object like the example below
   var Employee = {
      ID: 1,
      FirstName: "Jeff",
      LastName: "Jordan",

      displayEmployee: function() {
          document.writeln("Employee ID: " + this.ID);
          document.writeln("First Name: " + this.FirstName);
          document.writeln("Last Name: " + this.LastName);
};




The mutabiity of a JavaScript object

Unlike traditional programming languages such as C# or Java, when you work with a JavaScript object you can add a property or method to an object dynamically. For instance let's say you've already declared the Employee object and you wanted to add the property "Title" to object. How would you do this? Well in a C# or Java you would have to go back to the class definition and add the property in the class definition file. But in JavaScript you can add the property dynamically in your code as you need it. Like the example below.
   var Employee = {
      ID: 1,
      FirstName: "Jeff",
      LastName: "Jordan",

      displayEmployee: function() {
          document.writeln("Employee ID: " + this.ID);
          document.writeln("First Name: " + this.FirstName);
          document.writeln("Last Name: " + this.LastName);
};

   Employee.Title = "CEO";

Accessing Object Methods and Functions

You access the object methods and functions with the . notation. Meaning if you want to access the value for the employee's first name you would access it like this Employee.FirstName. Like the example below:

   document.writeln("Employee ID: " + Employee.ID);
   document.writeln("First Name: " + Employee.FirstName);
   document.writeln("Last Name: " + Employee.LastName);

Setting Object Properties And Methods

You can set object properties and methods in two ways. Either with the object name followed by a . and then the property/method name, or the object name with the property/method name enclosed within a [ ]
Employee.FirstName = "Jackie";
Employee["LastName"] = "Johnson";

Deleting Object Methods Or Functions

Let's say your object is getting too big and you want to eliminate some of the properties and methods that you are not using. Here is how you can do it.
delete Employee.displayEmployee;
delete Employee["Title"];

No comments:

Post a Comment