I know I can init an array of JS objects like this:
var things = [
{
prop1: 'foo',
prop2: 'bar'
},
{
prop1: 'foo',
prop2: 'bar'
}
];
I guess I would call these 'anonymous' types (sorry, I'm using C#/.NET language).
What if I want these to be of the same prototype? So I have defined a constructor:
var Thing = function Thing() {
};
Thing.prototype.prop1 = 'default value';
Thing.prototype.prop2 = 'default value';
Now I want both the items in my original code above to be Things. Is there a good way to do this?
If I were to guess, I would say maybe something like:
var things = [
new Thing() {
prop1: 'foo',
prop2: 'bar'
},
new Thing() {
prop1: 'foo',
prop2: 'bar'
}
];
Which is basically C# object initializer syntax. What I'm trying to avoid is:
var thing1 = new Thing();
thing1.prop1 = 'foo';
thing1.prop2 = 'bar';
var thing2 = new Thing();
thing2.prop1 = 'foo';
thing2.prop2 = 'bar';
var things = [thing1, thing2];
Edit:
I should also note that my prototypes also contain some functions that are shared. Also in actuality I have arrays nested 3 deep, so its something more like:
{
[
{
[
{},
{}
]
},
{
[
{},
{}
]
}
]
}
Which is why I as hoping to just init everything inline like this and not setting each property line by line.