First thing to understand: with JavaScript, you don't need lists or other collections. There is only one collection, a JavaScript object (of type 'object'), which has one specialized form, array, with only one difference: it has the property
length
. Everything is organized as key-value pairs, elements of an
associative array, which gives your the
time complexity of O(1) for search-by-key:
https://en.wikipedia.org/wiki/JavaScript#Dynamic[
^],
https://en.wikipedia.org/wiki/Associative_array[
^],
https://en.wikipedia.org/wiki/Big_O_notation[
^],
https://en.wikipedia.org/wiki/Time_complexity[
^].
This is the "regular" object:
var object = {a:1, b:"some value"};
The only difference for array is that is has integer-indexed properties which are automatically counted under the property
length
, for example:
var array = ["a", "b", "c"];
array.someProperty = 12323;
array[13] = 12;
Notably, you can always add a "regular" property (
someProperty
; in this example) to any object (array, function, anything). The length in this example is 14. All the indexed values under any integer indices except assigned are
undefined
.
The remaining piece is using
new
. If a function is called with
new
, it returns some object from prototype (even if you don't have a prototype, some default prototype object is used), and the clone of prototype is returned, with all properties you assign through
.this
added.
To make and example of what you want, I would need to know what do you want to have in items. As I have no idea, you can think about it yourself, say, add the items later. Also, I want to fix your big problem: hard-coded
immediate constants like "alert-warning". So, you can have:
var Severity = {alertDanger:1, alertWarning:0}
var Change = function (category, items) {
this.Category = category;
if (!items)
this.Items = []
}
var Item = function(item, from, to, requiresAuth) {
this.Item = item;
this.From = from;
this.To = to;
if (requiresAuth)
this.Severity = Severity.alertDanger;
else
this.Severity = Severity.alertWarning;
}
var itemsArray = [new Item("item1", 1, 3), new Item("item 2", 3, 4, true)]
var firstChange = new Change("NoItems");
var secondChange = new Change("Details", itemsArray);
[EDIT] This code sample was modified after your clarifications of the question. Feel free to ask your follow-up questions if something is not clear.
For working with arrays (which you may not need), see the first code sample and my explanations.
For working with prototypes and prototype chains, please see my recent answer:
What is happening there related with prototypes?[
^].
See also:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects[
^],
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object[
^].
—SA