JavaScript object literals and complex values

Object literals are JavaScript objects that cannot be instantiated with the new operator. So with an object literal like this:

var myObject = {
  property: value
};

you cannot use something like this:

var instance = new myObject();

because myObject is not a constructor. Period. The important thing to note here is that object literals can actually store only simple values, not complex ones. So if you write something like this:

var myObject = {
  url: location.href
};

you get undefined. If you really want to store complex values within an object literal, you should use methods and not properties, like this:

var myObject = {
  url: function() {
    var href = location.href;
    return href;
  }
};

That's all.

Leave a Reply

Note: Only a member of this blog may post a comment.