560 Part IV: Appendixes
Object Creation
Objects are created using the new operator in conjunction with a special constructor function.[var] instance = new Constructor(arguments);For example, here we create a new Date object that is built-in to ECMAScript:var today = new Date();Constructor functions are by convention named in uppercase and can be user defined.
This shows an example of creating a simple object Dog with one property and method.function Dog(name)
{
this.name = name;
this.bark = function () { alert("woof woof!"); };
}var angus = new Dog("Angus Dunedin Powell");
alert(angus.name);
angus.bark();Besides constructing objects with new, it is also possible that Object literals may be
used with the following syntax:{ [ prop1: val1 [, prop2: val2, ...]] }For example:var myDog = {
name : "Angus"
city : "San Diego",
state : "CA" ,
friendly : true,
greeting : function() { alert("Ruff ruff!"); }
}Object literals are quite important in JavaScript today as they are being co-opted to
create a namespace-like wrapper around various user-defined variables and functions. For
example, given:var gServiceId = 5551212;
function send() { }
function receive() { }you would wrap the values and functions within an object literal like so:var fakeNS = {
gServiceId : 5551212,
send: function () { },
receive: function () { }
}and avoid polluting the shared global namespace with many identifiers.