wassermine
wassermine

Reputation: 131

create dynamic Object (as function(...))

I create an object with dynamic properties during runtime in JavaScript.

It simply works like that:

var object = {
    'time' = ""
};

After that, I'm able to add more properties, for instance, like that:

var propName = "value1";
object[propName] = "some content...";

But I need to work with a real object, so that I can create a new instance, e.g.: var myObject = NewObject('myTime', 'myValue1', 'myValue2' ...);

For creating a static custom object I would do this:

function NewObject(time, val1, val2, ... valn) {
    this.time = time;
    this.val1 = val1;
    ...
}

But I have no idea, how to design such a function dynamically, depending on different user input my NewObject could have 1 to n value properties...?

I know, I would be better to implement a List or Array, but I would like to know, if there's a solution for my problem?

Thanks for your help.

Upvotes: 0

Views: 140

Answers (1)

Passerby
Passerby

Reputation: 10070

You can use the arguments object inside function:

function NewObject(time){
    this.time=time;
    if(arguments.length>1){
        for(var i=1;i<arguments.length;i++){
            this["val"+i]=arguments[i];
        }
    }
}

JSFiddle

Upvotes: 1

Related Questions