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. In various languages a collection of name and value pairs is called things like record, struct, dictionary, hash table, keyed list, or associative array. Contrast the object concept with the JS Array: An ordered list of values, aka: vector, list, or sequence./p>
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: Prototype 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 either a constructor function or on the fly. 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.
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 while properties are deleted, 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.
//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.
//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:
Properties and methods can be added to all objects of the type Object. This extension is usually done either on the object's prototype or on object instance itself.
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, a "class" is simply a function object (functions are objects in JavaScript) called a prototype constructor. Prototypes are more flexible than classes and hence the distinction.
FYI: The root "proto" is from the Greek for "from", so "from type" as in "archetype".
A prototype constructor function can be used to make instances of itself, and can be modified.
function Dog() {
this.avm = 'animal';
this.speak = function(){ alert('bow wow!') }
}
var fred = new Dog(); //"new" invokes a constructor
//The .prototype property can modify the prototype ("class")
Dog.prototype.speak = function(){ alert('ruff ruff!') }
Dog.prototype.legs = 4;
//The .constructor property is inherited from Function.prototype
//.constructor provides a reference to the constructor function
fred.constructor == Dog; //true
HOWEVER, JavaScript also provides a way to instantiate objects ex nihilo ("from nothing"), i.e. without a "class" or prototype, by using literal object notation {}, aka JavaScript Object Notation (JSON). FYI: JSON is also an data interchange format that is human and computer readable comparable to XML.
var fred = {
avm: 'animal',
speak: function(){ alert('bow wow!') }
}
fred.prototype.legs = 4; //errs. prototype unapplicable
fred.constructor == fred; //false. The "constructor" is native code
Returns a boolean indicating whether this object contains the specified property directly (instead of inherited through the prototype chain).
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
Returns a boolean indicating whether this prototype is in the prototype chain of the passed object.
function A(){};
function B(){};
function C(){};
B.prototype = new A();
C.prototype = new B();
var c = new C();
document.write(A.prototype.isPrototypeOf(c));
Returns a boolean indicating whether this object has the passed property directly and that property can be enumerated by a for ... in loop.
var a = [1,2,3]; alert(a.propertyIsEnumerable(0)); //alerts true alert(a.propertyIsEnumerable('length')); //alerts false cuz inherited alert(a.propertyIsEnumerable('foo')); //alerts false cuz undefined a.foo='foo'; alert(a.propertyIsEnumerable('foo')); //alerts true cuz defined
Implemented: JS 1.3; ECMA-262 not.
Returns a string representing the source code of the object or a literal if possible.
function dbl(n) {return n+n}
alert(dbl.toSource()); //returns 'function dbl(n) {return n + n}'
alert([1,2,3].toString()); //returns '[1, 2, 3]'
Implemented: JS 1.1; ECMA-262.
Returns a string representing the object.
function dbl(n) {return n+n}
alert(dbl.toString()); //returns 'function dbl(n) { return n + n }'
alert([1,2,3].toString()); //returns '1,2,3'
var dtm = new Date();
alert(dtm.toString());
//returns something like 'Wed Sep 17 2008 11:46:36 GMT-0500 (Central Daylight Time)'
Implemented: JS 1.2; ECMA-262 not.
Unwatches a watchpoint set with .watch().
Implemented: JS 1.1; ECMA-262.
Returns a string representing the primitive value of the object.
var ary=[1]; alert(ary.valueOf()); //'1,2' var bln=false; alert(bln.valueOf()); //'false' var dtm=new Date(); alert(dtm.valueOf()); //ms since midnight 01 January, 1970 UTC var fun=function(n){return n+n}; alert(fun.valueOf()); //'function (n) { return n + n; }' var mth=Math.PI; alert(mth.valueOf()); //'3.141592653589793' hehe var num=1; alert(num.valueOf()); //'1' var obj={a:1}; alert(obj.valueOf()); //'[object Object] var reg=/1/gi; alert(reg.valueOf()); //'/1/gi' var str='1'; alert(str.valueOf()); //'1'
Implemented: JS 1.2; ECMA-262 not.
Watches the passed property of the object and runs the passed handler function of the passed property is assigned a value. The passed handler function takes 3 parameters: property, oldValue, and newValue.
var o = {p:1};
o.watch("p",
function (ppty, oldval, newval) {
alert("o." + ppty + " changed from " + oldval + " to " + newval);
return newval;
});
o.p = 2;
o.p = 3;
delete o.p;
o.p = 4;
o.unwatch('p');
o.p = 5;
Page Modified: (Hand noted: 2008-08-14 19:37:08Z) (Auto noted: 2010-12-24 22:48:14Z)