Abdul Rauf
Abdul Rauf

Reputation: 484

Copy object functions and properties in new object by value not by reference - javascript

I want to copy the functions and properties of an object into new object. The old object should not effect by changing made in new Object.

Here is the object definition:

  var Call = function() {
        this.number="123";
    }
    Call.prototype.function1 = function() {
         return this.number;
    }
    var callobj = new Call();

I can access function1 using callobj.function1().

What I have tried to copy it:

Javascript:

var newcallobj = Object.assign({}, callobj);

In this case, i am not able to access function1 but i can access number property directly.

JQUERY:

var newObj = jQuery.extend(true, {}, callobj); OR 
var newObj = jQuery.extend({}, callobj);

In this case, i am able to access function1 and property but when i change number like that newObj.number="222". It also change the value of original object.

I know that there is couple of other posts. But all is not working for me. Please let me know if i am doing any thing wrong?

AFTER @gurvinder372 answer(I am updating question): After @gurvinder372 answer. It is working for first level of property but if it has another object like i show below and i change the value of property of another object. Then it is effecting on original object also.

var ABC = function(){
    this.number = "333";
}
var Call = function() {
    this.number="123";
    this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
     return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);

Output of both is 123. @gurvinder372. can you check th above code ?

Upvotes: 0

Views: 56

Answers (2)

Abdul Rauf
Abdul Rauf

Reputation: 484

Ok. By the help of @gurvinder372. The following solution is working for me.

var ABC = function(){
    this.number = "333";
}
var Call = function() {
    this.number="123";
    this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
     return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj = Object.create(callobj.anotherobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);

Please let me know if there is any better solution other than this?

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

Object.assign only copies the enumerable properties of an object.

Use Object.create instead of Object.assign

var newcallobj = Object.create(callobj);

var Call = function() {
    this.number="123";
}
Call.prototype.function1 = function() {
     return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
console.log(newcallobj.function1());

Upvotes: 2

Related Questions