Monday, November 25, 2013

Making Javascript Objects

There are several ways to create a javascript object. In this dive I wanted to take a quick look at a little of what is created under the hood for some of them (I think there are several other ways to do this as well).

In each case below, the details were obtained via a screenshot of
console.dir(myObject)
in the Google Chrome browser.

Method   Code & Initial Details
Object Literal
   var myObject = {"myProperty": 42};
Create Object Literal
via a Function

   function MakeMyObject() {
      return {"myProperty": 42};
   }    
   var myObject = MakeMyObject();
Create Object Literal
via a Function that
has Local Variable

   function MakeMyObject() {
      var myInternalProperty = 1;
      return {"myProperty": 42};
   }    
   var myObject = MakeMyObject();
Use Function as Constructor

   function MyObject() {
      this.myProperty = 42;
   }    
   myObject = new MyObject();

The most obvious difference here is what happens when the
new
operator is used with the function. However, while the screenshot of the others is identical, there are differences based on the associated closures with each function. There is a way to dive into this with Chrome's Heap Profiler, but I haven't yet figured out an easy way to get that out.

Using the
new
operator lets you easily create lots of different objects of the same type - you can add constructor arguments to facilitate customizing each one.

More Reading

No comments:

Post a Comment