tags:

views:

141

answers:

5

Possible Duplicate:
Copying an Object in Javascript

How can I create a new object from other object? Something like copy constructor in other languages like C#.

+1  A: 

This might be helpful:

Copying Objects in JavaScript

karim79
A: 
Alsciende
The `prototype` property should be used on Constructor Functions, on object instances *has no special meaning*, there is a lot of confusion between that property with the internal `[[Prototype]]` property...
CMS
This looks like an interesting solution, but in testing it doesn't work.
Renesis
right, my mistake. i'll correct it
Alsciende
+2  A: 

There is no built-in framework for copying in JS. Many of the simple types are immutable value types which you can just copy the references of. Array and Object you can write a function to copy for you, eg.:

function copy(o, isdeep) {
    if (o===undefined || o===null || ['string', 'number', 'boolean'].indexOf(typeof o)!==-1)
        return o;
    var n= o instanceof Array? [] : {};
    for (var k in o)
        if (o.hasOwnProperty(k))
            n[k]= isdeep? copy(o[k], isdeep) : o[k];
    return n;
}

However for every other type of object you will have to write your own copy code. Many built-in objects are inherently uncopiable.

bobince
I think that OP meant 'clone' object and not 'copy' (event if he didn't say so). You show how to create a new instance of an object with copy of all its properties (e.g. same property in the result object will point to the same memory as the property of source). This mean that changing some property in source object will change this property in destination object.
Kamarey
A: 

//

function copycat(obj){
    if(!obj.constructor) return obj;
    var cop= new obj.constructor;
    for(var p in obj){
        if(obj.hasOwnProperty(p)){
            cop[p]= obj[p];
        }
    }
    return cop;
}

var a= [1, 2, 3, 4, 5];

var o={x:100,y:100,z:100};

var b=copycat(a);

var o2=copycat(o);

kennebec