An Introduction to JavaScript Objects

Posted on 9/29/2014 @ 9:43 PM in #Bak2Basics by | Feedback | 2031 views

There are three kinds of objects in JavaScript,
1.    Built in objects like Object, Array, Function, etc.
2.    Objects that you create like this var x = {};
3.    Objects that are created for you like document, window etc.

You can create your own objects in many ways,

   1:  // like this 
   2:  var o = {};
   3:  var o = new Object();
   4:  var o = {x:10, y:10}
   6:  // or like this .. read further below, you can use similar concept as below to do singleton also
   7:  function CoolDude(firstName, lastName) {
   8:      this.firstName = firstName;
   9:      this.lastName = lastName;
  10:  }
  12:  var sahil = new CoolDude("Sahil", "Malik")
  14:  // Or using Object.Create (more on this later)
  15:  var point = {x:10, y:10} ;
  16:  var point3d = Object.create(point) ;
  17:  point3d.z = 10 ; // this will have x,y,z axes.


Object Properties

Objects can have properties, those properties can point to scalar objects, other objects, or even functions, like this –

   1:  var myObject = {
   2:      scalarProperty: 1,
   3:      anotherObject: {firstProperty: "I'm First"},
   4:      functionProperty: function(inputVal) {
   5:          alert(inputVal.firstProperty);
   6:      }
   7:  };
   9:  myObject.functionProperty(myObject.anotherObject);


Object Prototypes

  • All objects have prototypes. Even if you don’t declare any properties in an object, it still has some properties,
    1.    valueOf()
    2.    hasOwnProperty
    3.    isProtoTypeOf
    4.    propertyIsEnumerable
    5.    toLocaleString
    6.    toString
    These are the same properties on Object.prototype.
    So if any object does not have a prototype defined, the object will look up Object.prototype and give you that default implementation. You can of course override the definition of any of those properties for your object.

You can use Object.create to do reuse of objects. A bit like this,

   1:  var point = {x:10, y:10} ;
   2:  var point3d = Object.create(point) ;
   3:  point3d.z = 10 ; // this will have x,y,z axes.

Property – Data Descriptor

The object properties hole can go quite deep. For one, you can make read only properties like this,

   1:  var myObject = {}; 
   2:  Object.defineProperty(myObject, 'myProperty', {
   3:    value: 20,
   4:    writable: false,
   5:    configurable: false
   6:  });

But remember that JavaScript is quite free-form, so if the user of your object wishes to make it writable, he can. But by default, you can’t change the myProperty’s value once it is set. The configurable attribute allows you to say whether a property can be deleted from the object or not, or whether it’s attributes can be changed.

Another property you have available is “enumerable” so you can use on it.

Property Assessor descriptor

One of the really cool things you can do with properties, is you can set get/set assessors. In other words, some code that gets called when you either set the property value, or get the property’s value. A bit like this,

   1:  var myObject = {};
   3:  Object.defineProperty(myObject, 'GetSetFunProperty', {
   4:      get: function() {
   5:          console.log('get!');
   6:          return GetSetFunProperty;
   7:      },
   8:      set: function(value) {
   9:          console.log('set!');
  10:          GetSetFunProperty = value;
  11:      }
  12:  });

So over here, you can say set customer.FullName automatically if either FirstName or LastName are called.

Querying property details

You can at runtime query the property details (think reflection) using the below,

   1:  Object.getOwnPropertyDescriptor(myObject, "GetSetFunProperty")

You can get a list of all properties exposed using

   1:  Object.getOwnPropertyNames(myObject)


Functions –standard procedures blocks of code that you can call, can be declared in 2 ways,

   1:  function sum(x,y) {
   2:      return x+y;
   3:  }
   5:  var sumFunc = function(x,y) {
   6:      return x+y;
   7:  }


So a function can be treated as a property, as a value, or as a function. So a function can be passed around like a value.

Since function is an object, it also has an object prototype. But it’s object prototype has some notable differences compared to a simple object variable’s prototype.

•    You can use “caller” inside function to find out which function called your function.
•    You can use the “arguments” object inside the function to get a hold of arguments passed to the function.
•    You can call function.prototype.constructor to find out the function that creates an object’s prototype.
•    You can call to call the function
•    Length property gives you number of parameter it takes
•    toString shows you function implementation
•    call calls the function


Functions have their own scopes, so you can use self calling functions to isolate your code from the global object, like this –

   1:  (function(){
   2:    // your code goes here  
   3:  })();

And this can also be used to define scope of variables, for instance below, the outer variable is available inside,

   1:  (function(){
   2:    // your code goes here  
   3:      var outer = "I'm outside";
   4:      function() {
   5:          // outer is available here
   6:      }
   7:  })();

and similarly, you can isolate yourself from outside, this is a great way to get thread consistency

   1:  (function(){
   2:    // your code goes here  
   3:      var outer = "I'm outside";
   4:      function(outer) {
   5:          // outer is available here, but as the value of outer changes outside, it is not seen inside. Good way to isolate yourself, say for loop iteration.
   6:      }
   7:  })();

Sound off but keep it civil:

Older comments..