Reputation: 522
I have decided (whether bravely or foolishly remains to be seen) decided to increase my javascript skills beyond the use of alerts and I've been looking at using javascript business objects with the hope of creating a useful library of objects that I can then manipulate with JSON or XML further on down the line.
The basic concepts are straightforward enough but I can't seem to find an example anywhere of how to expose a property of an object that is a collection of a different type of object.
For instance if I have a "Department" object I would like to have an "Employees" property which is a collection of "Employee" objects.
I'm from a .Net background so I might be coming at this with the completely wrong mindset here but if I am I'd like to learn the right way to approach this.
Is the concept still applicable in javascript, can a property of a javascript object be a collection of another type of object? Does the concept of a collection even exist (I'd like to be able to enumerate through the collection too) or should I be thinking in terms of arrays or something else?
Here is some pseudo code which should illustrate what I'm aiming for:
function Department (Name)
{
this.DepartmentName=Name;
this.Employees = null; // How do I initialise a property to be a collection of Employee objects?
}
function Employee(FirstName, Surname)
{
this.EmployeeName = Firstname + ' ' + Surname;
}
Department.prototype.addEmployee = function (Firstname, Surname)
{
//In here I want to create an Employee object and add it to an
//'Employees' property of the department object
}
Upvotes: 3
Views: 1230
Reputation: 154908
There is no real "list of objects of a specific type" in JavaScript. You seem to just want an array, which is a "collection" (basically an object) with numeric keys and values which can be everything (JavaScript is dynamic, so there is no easy way to force a collection to contain only items of one type, but you should never need to anyway):
function Department (Name)
{
this.DepartmentName = Name;
this.Employees = []; // empty array
}
Then in the prototype function, you can:
Employee
this.Employees
Like:
Department.prototype.addEmployee = function (Firstname, Surname)
{
// adds to the end of the array
this.Employees.push(new Employee(Firstname, Surname));
};
You can access the Employee
objects like this.Employees[0]
, etc.
Don't forget the semicolon at the end of the prototype function. It's a function expression, and it's good practice to terminate function expressions with a semicolon. Function declarations (like for Department
and Employee
), on the other hand, do not need those. The difference is that the prototype function is used as an expression in the assignment statement.
Moreover, CapitalCase
is usually used for constructors (Employee
); regular variable names are usually names in camelCase
.
Upvotes: 5