Gerry Gry
Gerry Gry

Reputation: 182

how to create new instance of object in javascript

I'm having difficulties to create new instance from an object in javascript. Try to read some answer, but still no luck.

var general_obj = {
    title : '',
    count : 0,
    details : [],
    status : 'OK'
}

function processData(input){
    var result = Object.create(general_obj);

    return result;
}

I wanted to create new instance from general_obj. I'm expecting the result would have the same structure as general_obj, whereby in my case the return become only

{}

instead of:

{
    title : '',
    count : 0,
    details : [],
    status : 'OK'
}

How can I achieve it ?

Upvotes: 0

Views: 3272

Answers (3)

Sandman
Sandman

Reputation: 2307

Try the following instead:

function general_obj(title, count, details, status) {
    this.title = title;
    this.count = count;
    this.details = details;
    this.status = status;
}

Then instantiate with:

var result = new general_obj("", 0, [], "OK");

Upvotes: 0

maik mr
maik mr

Reputation: 67

var general_obj = {
    title : '',
    count : 0,
    details : [],
    status : 'OK'
}

function processData(input){
    var result= (JSON.parse(JSON.stringify(general_obj)));

    result.title = 'two';
    result.count = 10;
    result.details.push({
        "in-hand": 4,
        "warehouse": 6
    });
}

With json you can clone your object...

Upvotes: -1

Horia Coman
Horia Coman

Reputation: 8781

You may want to use Object.assign({}, general_obj) to create a new object, but with all fields copied from general_obj.

Keep in mind that this is a shallow copy however, and both the new instance and old one would be pointing to the same array through the details field.


The Object.create function allows you to specify a prototype for the object that is created, which would result in similarish behaviour to what you want functionally, will result in you seeing the results you're observing.

Upvotes: 3

Related Questions