Object is the primitive JavaScript object type. All other JavaScript objects inherit from Object, so this page will discuss objects in JavaScript in general.

Intro

In essence, an object is a container of members (properties, methods, sub-objects) indexed by name, whereas an array is a container of things indexed by number.

JavaScript is object-oriented but is prototype-based instead of class-based. In class-based object-oriented programming languages an object can only be instantiated via a class and its class constructor. The class defines members (properties in a structure and methods) as well as inheritance (behavior reuse). In prototype-based object-oriented programming languages an object can be created ex nihilo ("from nothing") or by cloning an existing object (i.e. a prototype). FYI: The root "proto" is from the Greek for "from", so "from type" as in "archetype".

//Object instantiation ex nihilo
var MyObj = {
    MyValue: 78,
    MyFunction: function() {
        alert("You just ran MyObj.MyFunction. MyObj.MyValue is "+ this.MyValue);
    }
}

//Object instantiation via prototype
//Step 1: Protype constructor
function MyPrototype() {
    this.MyValue = 13;
    this.MyFunction = function() {
        alert("You just ran MyPrototype.MyFunction. MyPrototype.MyValue is "+ this.MyValue);
    }
}
//Step 2: Instantiations
var MyObj1 = new MyPrototype();
var MyObj2 = new MyPrototype();

Basic Usage

A JavaScript object is made/instantiated by using a constructor function. EGs:

var o1 = new Object(); //Instantiates a blank object
var o2 = new String("hi"); //Instantiates a built-in JavaScript native object
var o3 = new Dog("Spot", "Greyhound"); //Instantiates an object user-defined elsewhere
var o4 = {name:"Fred",age:13,pet:o3}; //Instantiates an object on the fly with JSON

A constructor function defines the object class/prototype by specifying the name of the class/prototype and its members. Instantiating an object is basically allocating memory for your object. See also my more general article on Objects. EG:

function sayIt(){ //Functions are also constructors
	return "I am " + this.name;
}
function Dog(name) { //This constructor function defines the prototype/class "Dog"
    //Properties of Dog
    this.name = name; //Note the use of the "this" operator.
    this.sex = "M"; //Properties do not have to be parameters for the constructor
    //Methods of Dog
    this.say = sayIt; //Add method by referencing outside function statement. Note the absence of parentheses.
    this.bark = function() { //Add method by referencing an in-line function expression.
        return "Bow Wow!";
    }
    //Sub-object of Dog
    this.house = new Object();
    this.house.color = "red";
}
var myDog = new Dog("Spot");  //This instantiates the object myDog 
myDog.sex = "F"; //Modifies a default value
alert(myDog.say()); //Says "I am Spot"
alert(myDog.bark()); //Says "Bow Wow!"
 //Here's proof that the object was made:
alert(myDog instanceof Dog); //true
alert(myDog instanceof Object); //true 
alert(myDog.constructor == Dog); //true
alert(myDog.constructor); //gives the definition
alert('sex' in myDog); //true, member in object
alert('age' in myDog); //false, member not in object

Additional members can be added by three ways:

//Instance/object extension, i.e. for this specific instance/object
myDog.color = "Brown"; //property and value
myDog.bite = function() { //method
    return "oww!";
}
var aDog = new Dog("Joe");
alert('color' in aDog); //false, aDog does not have the color property that myDog does
alert('sex' in aDog); //true, aDog does have the sex property
//Class/prototype extension, i.e. for all instances/objects of the class/prototype
Dog.prototype.smell = "ok"; //property and default value
Dog.prototype.toString = function() {return this.name;}; //Overwrites the toString() method it inherited
//All old and new instances of the Dog class now have the new members
alert(myDog.smell); //smell is ok
alert(aDog.smell); //smell is ok
var leDog = new Dog("Pepe");
alert(leDog.smell); //smell is ok
//Class/prototype inheritance, i.e. from a parent/super class/prototype to a child/sub class/prototype
function XDog(){
    this.finds = "bombs";
}
SearchDog.prototype.constructor = XDog;//You could have a class/prototype whose constructor has a different name
SearchDog.prototype = new Dog();
var heroDog = new SearchDog();
alert(heroDog.sex); //'M', proves the inheritance
alert(Dog.prototype.isPrototypeOf(heroDog)); //true, Dog is parent/super class/prototype of SearchDog
alert(Object.prototype.isPrototypeOf(heroDog)); //true, Object is also part of the class/prototype chain

Properties can be deleted with the delete operator. Note that properties are deleted, but objects are destroyed automatically by garbage collection in JavaScript. This is like c# but not like Java or VB. EGs:

o = new Object;
o.myInit = "x";
alert("myInit" in o); //true
alert("myUnInit" in o); //false  
delete o.myInit; //bye-bye property 
alert(o.myInit===undefined); //true alert("myInit" in o); //false 

The object versions of primitive types offer many useful features.  EG:

//Using the string primitive type:
var s1 = "2 + 2"	// creates a string literal value
eval(s1)		// returns the number 4
//Using the String object:
var s2 = new String("2 + 2")	// creates a String object
eval(s2)		// returns the string "2 + 2"
s2.substring(1,2)	//returns "2 "

Arrays are objects, objects are like arrays, and the syntax for getting at members in either is nearly interchangeable. EG:

//array notation can be used for properties. 
Math["PI"]; //Object dot notation would be Math.PI 
//array notation can be used for methods
document["write"]("hi")  //Object dot notation would be document.write("hi") 
var hisData = new Array(2);
hisData[0]  = "cat";
//hisData.0 will not work because the 1st character of a property cannot be a #.

var herData = new Object;
herData["heightCM"] = 61.5;  //just like herData.heightCM 
alert("length" in herData); //Returns false. //Not all objects have a length property but all arrays do

Object collections have several advantages over arrays.

With a JavaScript object, it is very easy to make private, public, and privileged members (variables, methods, and objects), as well as namespaces.

EG:

MyNS = {}; //Creates an object used as a namespace.
//Within the obj/ns, run an anonymous function operator/expression to create a module/class.
MyNS.MyModule = function(MyParam) { //MyParam is a private variable to this function, i.e. accessible only within MyNS.MyModule as MyParam.
    var MyPrivateVar = "MyPrivateVar"; //A private variable, i.e. accessible only within MyNS.MyModule as MyPrivateVar.
    var MyPrivateFun = function () { //A private method, i.e. accessible only within MyNS.MyModule as MyPrivateFun().
        return "MyPrivateFun" 
    }
    var that = this; //A private variable set to the context/current/calling object
    this.MyVar = MyParam; //The private MyParam exposed as the privileged MyVar
    return { //Return a JSON object
        MyPublicVar: "MyPublicVar" //A public variable. Does not access private stuff.
        , MyPublicFun: function () {
            alert("MyPublicFun"); //A public method. Does not access private stuff.
        }
        , MyPrivilegedVar: "MyPrivilegedVar"+MyPrivateVar; //A privileged variable. Accesses private stuff.
        , MyPrivilegedFunL function () { //A privileged method. Accesses private stuff.
            alert("MyPrivilegedFun"+MyPrivateFun());
        }
    }
}();//Self-invoke so that MyNS.MyModule gets public and privileged members

Here are some links that discuss OOP and JS:

Properties

.prototype. Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class.

These properties are inherited from Function.prototype: .caller, .constructor, .length, .name.

.constructor. Returns a reference to the Object function that created an object's prototype. References the function itself and not just the function's name. EGs:

var o = new Object; // or o = {} in JavaScript 1.2
o.constructor == Object; // returns true
var a = new Array; // or a = [] in JavaScript 1.2
a.constructor == Array; // returns true
var n = new Number(3);
n.constructor == Number; // returns true

For really fast on the fly objects, JSON (object literals or name:value pairs in curly brackets) can be used for JS 1.2+. EG:

var mycar = {make:"Honda",model:"Accord",year:1998,sold:{y:2004,m:1,d:22}};
mycar.make = undefined;
"make" in mycar;  // returns true
mycar.constructor == Object; // returns true
delete mycar.make;
"make" in mycar;  // returns false

Methods

These methods are inherited from Function.prototype: .apply(), .call(), .toSource(), .toString(), .valueOf().

These methods are inherited from Object.prototype: __defineGetter__(), __defineSetter__(), hasOwnProperty(), isPrototypeOf(), __lookupGetter__(), __lookupSetter__(), __noSuchMethod__(), propertyIsEnumerable(), unwatch(), watch().

2007-08-08 18:25:01Z