I've created a Javscript prototypal object with a range of attributes. And I need to pass some of these attributes to a function. The function processes the attributes and returns some result.
function ObjCt(id,data) {
this.id = id;
this.data = data;
}
So, I'm trying to pass the data of the chart object to a function. Im calling it as:
var obj=new ObjCt(id,data);
process(obj.id,obj.data);
I read from somewhere that passing a value in JS results in a call by value and passing an object results in a call by reference. Here I am trying to call by value, but, seems whatever processing happens in the process()
function is reflected in the object obj
.
I checked the variable received in the process function using typeof
and it comes up as 'object' and not variable. So, what can I do to pass this data as a value?
Edit
I found a rather tiresome workaround. id
is primitive and data
is a JSON object. So, I tried this in the process()
function
JSON.parse(JSON.stringify(data))
Apparently, all references were slashed here. I have a working implementation now, but, Id still love to see if there is an easier way for passing an attribute as a value.
Edit
Solved the problem. As per Paul's answer, tried a normal step by step cloning and another alternative using jquery extend method which goes like this
var object=$.extend(true,{},oldObject);
and passed the newly created object to the process()
function.
Please refer this link: What is the most efficient way to deep clone an object in JavaScript?