Magic of Javascript Object literal

I like this concept very much, You can create a fully function Object with its properties and methods using JSOL. Eventhough you do not have a Class function to define it, isn’t that beautiful.
Below is the example of a Employee Object Example, Notice the  colon(:) separate name value pairs for member variables and it business logic functions
 //http://jsfiddle.net/mbhatamb/4JYQH/  
 //Below is the Description of Employee Object, in a simple way  
 Employee e = new Object();  
 e.firstName = "John";  
 e.lastName = "tester";  
 e.getFullName = new function() {  
   return this.firstName + " " + this.lastName;  
 }  
 console.log(e.getFullName());  
 //Below is the creation of a Employe Object, in Object literal Notation  
 Employee e1 = {  
 firstName : "john",  
 lastName : "tester",  
 getFullName : new function() {  
   return this.firstName + " " + this.lastName;  
 }  
 console.log(e1.getFullName());  

Also, see how remarkably JSOL is similar to a JSON , so when a JSON comes it can be easily and naturally converted to JSOL and vice versa.
Important things to remember
  • If there are more than one objects, you need to repeat this process of creating Objects! appears too cumbersome right! but this feature allows to easily create objects from JSON
  • Note the this keyword, it represents the objects getting created in methods, allowing easy access to member variables
  • Take a note of the syntax, colon separated name value pairs and comma separated members.
Thank you

Comments

Popular posts from this blog

Apache Airflow Wait Between Tasks

Groovy GoodNess – Converting a List to String

Java Spring Interview Questions