Object is the primitive JavaScript object type. All other JavaScript objects inherit from Object, so this page will discuss objects in JavaScript in general.
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();
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:
object.NewMember to the specific instance/instance of a class/prototype.ClassPrototype.prototype.NewMember, and those members are added to all instances/objects of the class/prototype.object.prototype = new ParentConstructor() from a parent/super class/prototype to a child/sub class/prototype.//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.
document[str].area, controlRange, and option collections can be inserted with .add(). EG:
<select id="oSelect">
<option value="1">One</option>
</select>
<script>
var oOption3 = document.createElement("option");
oSelect.options.add(oOption3); //Add to end of collection by default
oOption3.innerText = "Three";
oOption3.value = "3";
var oOption2 = document.createElement("option");
oSelect.options.add(oOption2,1); //Index of addition can be specified.
oOption.innerText = "Two";
oOption.value = "2";
</script>
area, controlRange, and option collections can be deleted with .remove(). EG: oSelect.options.remove(3);..item() or .children. EG:
var col0=document.all.item("myCollectionElement");
var obj1=document.all.item(3);
var obj2=document.all.item("myCollectionElement",3);
var colA=objA.children;
var xB1=objB1.children(3); //May return collection or object.
var xB2=objB2.children("yada"); //May return collection or object.
var objC=objC.children("myCollectionElement",3); //Should return object.
.length. EGs:window.length //Returns # of frames in a window. commentA.length //Returns # of characters in the element. (IE6+) selectA.length //Returns # of option element in the select collection.
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:
.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 truevar a = new Array; // or a = [] in JavaScript 1.2 a.constructor == Array; // returns truevar n = new Number(3); n.constructor == Number; // returns trueFor 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
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().
__defineGetter__().
__defineSetter__().
hasOwnProperty(strProperty). Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain. EG:
var o=new Object;
o.prop='x';
o.hasOwnProperty('prop'); //true: It's not an inherited property
('toString' in o); //true; //true: It's inherited from Function.prototype
o.hasOwnProperty('toString'); //false: It's inherited from Function.prototype
isPrototypeOf(). Returns a boolean indication whether the specified object is in the prototype chain of the object this method is called upon.__lookupGetter__().
__lookupSetter__().
__noSuchMethod__().
propertyIsEnumerable().
unwatch().
watch().
2007-08-08 18:25:01Z