Reputation: 5234
I'm filling an array with a bunch of locally-instantiated javascript objects. The objects are created via a constructor. Is there a way to add additional properties to the objects without extending the constructor to include all possible input properties?
var item = function(name, id) {
this.name = name;
this.id = id;
this.sharedMethod = function() {
// do stuff
}
}
var someArray = [
new item("one", 1) {house: "blue", car: "new"},
new item("two", 2) {pet: "dog"},
new item("three", 3),
new item("four", 4) {potatoChips: "yes", random: "sure is"}
];
I know the braces in the above someArray example are illegal. Though, i'm not sure of the correct way to go about this approach. Is there some special syntax to accomplish this that retains the use of the constructors (for shared functions) but does not involve having to store each item in a var and then manually push them onto the array. I'd also like to avoid having to extend the constructor to include the multitude of various properties.
I've tried searching for awhile but cannot seem to come up with the proper search terms to locate the answer.
Upvotes: 0
Views: 33
Reputation: 21575
You can simply have a single variable that stores an object:
var item = function(name, props) {
this.name = name;
this.props = props;
this.sharedMethod = function() {
// do stuff
}
}
Then simply pass an object with several properties:
new item("one", {"house": "blue", "car": "new"});
You can also set them as properties directly, other than accessing them withprops.[property]
. By looping through than object and setting them as properties like so:
var item = function(name, props) {
this.name = name;
for(prop in props)
this[prop] = prop;
this.sharedMethod = function() {
// do stuff
}
}
Upvotes: 2