Standardista

CSS3, JavaScript and HTML5 explained

JavaScript Objects

Javascript: Things you should know

Note: This is part III of a "Javascript: Things you should know" series. I assume readers have an understanding of the core language. This section goes over objects at a very basic level. Most books cover objects in a confusing manner. Below are really simple examples which, if you have been confused, will hopefully make things make sense. The previous entry was JavaScript Switch Statement Quirks.

JavaScript Objects Demystified

Everything in JavaScript is an object except core types. true, false, null, undefined and numeric values are not objects. Strings, with the length property and numerous methods, are objects.

Most JavaScript objects are collections of name-value pairs. I think of objects as associative arrays. The "name" or key of an object is a string except for in the array object where it can be a string or a incremental integer. The value can be any JavaScript value, including an array or other object.

Creating a JavaScript Object

There are two basic ways to create an object which are semantically equal. You can declare an object using an object function and instantiate the object by using the "new" keyword or you can use the object literal method:

  • var obj = new Object();
  • var obj = {}; // object literal method

Assigning properties to an object

An object’s properties can be assigned with the dot operator or like an associative array::

obj.name = "Estelle";
obj["name"] = "Estelle";

the property values can be retrieved in a similar fashion

var myname = obj.name;

var myname = obj["name"];

The difference between using the dot operator versus the array method is that since the key value is a string, you can use reserved words for the "name". If you plan on creating property names based on user input, this can be aspirin for what otherwise would be a headache. Otherwise, the dot syntax is easier, and reserved words should not be used. Using a reserved word is a bad idea. Both the object name and property name are case sensitive.

obj.for = "Estelle"; // produces an error
obj["for"] = "Estelle"; // allowed

Object Literals

Object literal syntax can be used to initialize the entire object.:

var obj = {
  name: "Estelle",
  gender: "Female",
  outfit: {
     top: "t-shirt",
     bottom: "jeans",
     shoes: "hiking boots"
     }
}

You can chain it together:

obj.outfit.shoes; // hiking boots
obj["outfit"]["bottom"]; // jeans

Even though outfit in the example above seems like it is a newly created object within obj, it isn’t:

outfit.shoes; // error, since outfit is not defined
obj.shoes; // undefined, not an error, since obj is defined, but the property shoes has not been assigned a value

Assigning methods to an object

Methods are simply functions tied to objects. For example, toUpperCase is a method of the string object. The simplest way to attach a method to an object is to use an anonymous function:

var greeting = {
  name: "Estelle",
  message: "this was written by ",
  welcome: function(){
     alert("Objects now make sense");
     },
  sayhi: function(){
     alert(this.message + this.name);
    }
}

welcome is a method of the greeting object. Calling greeting.welcome();, with the parenthesis, will cause the alert.

sayhi is also a method of the greeting object. Calling sayhi.welcome();, with the parenthesis, will cause the alert. The this keyword refers to the object that is calling the function, and will be discussed in further detail in a future entry.

Method names are also case sensitive.

the Window object.

All variables that are not assigned as properties of other objects become properties of the window object.

var animal = {};
var myCat = animal.pet = "Sassafrass";

In this case, animal is an object, pet is a property of the animal object and myCat is a property of the window object.

The following all work and return "Sassafrass":

  • animal.pet;
  • window.animal.pet;
  • myCat;
  • window.myCat;

The following may not return what you expected:

  • pet; // throws an error as pet is a property of the animal object, not the window object
  • window.pet; // undefined
  • window.animal // evaluates to object.

Note: JSON, or JavaScript Object Notation, is a subset of JavaScript’s oject literal notation.

JavaScript Object Properties and Methods

All objects in javascript inherit from the Object object, and therefore inherit the properties and methods of Object, including:

  • constructor property
  • prototype property
    used to assign new properties and methods to future instances of the object type.
  • hasOwnProperty() method
  • isPrototypeOf() method
  • propertyIsEnumerable() method
  • toString() method
  • toLocaleString() method
  • valueOf() method

Extending Objects

It is fairly simple, though not always necessary, to extend objects with new methods and properties. Use the protoype property, inherited from the Object object to add methods to an object. Here are some examples of String, Array and Date object methods.

String.prototype.capFirst = function(){
   return this.charAt(0).toUpperCase() + this.substr(1);
}

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

Array.prototype.sortCaseInsensitive = function(){
    return this.sort(function(a,b){ return (String(a).toLowerCase() > String(b).toLowerCase())? 1: -1;}
}


Date.prototype.customFormat = function(formatString){
  //The code for this is in the javascript date object article.
}

Leave a Reply