Entry
How do I create an Object?
Mar 4th, 2000 20:18
Martin Honnen,
There are different ways of doing that, the simpliest a call of
new Object();
This creates an empty object to which you then can add properties e.g.
var person1 = new Object();
person1.name = 'James Kibo Parry';
person2.home = 'http://www.kibo.com';
Starting with JavaScript1.2 you can also write Object literals (like
you can write string literal e.g. 'string' or number literals e.g. 2):
var person1 =
{name: 'James Kibo Parry', home: 'http://www.kibo.com' };
so an object literal is just a list of name: value pairs enclosed in
curly brackets.
Suppose you want to store the data of many different persons all
sharing the same properties so
var person2 = new Object();
person2.name = 'Nathan Wallace';
person2.home = 'http://www.faqts.com';
etc. That task can be faciliated by defining your own object
constructor for these class/type of person objects:
function Person (name, home) {
this.name = name;
this.home = home;
}
which you then use as follows
var person1 =
new Person ('James Kibo Parry', 'http://www.kibo.com');
var person2 =
new Person ('Nathan Wallace', 'http://www.faqts.com');