0

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.

1 Answer 1

2

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 
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

but you'd have to access the custom properties via props. Why not, assign each of the key values from props to this?
@Munick I was just thinking maybe the OP want's to identify them separately from name. But yes, I'll add that way as well.
Thanks guys. The idea of iterating the props and adding to the main object sounds like a great solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.