Apologies for the unclear title, but I am unsure where the issue lies.
Therefore, my task is to create a function that generates JavaScript objects from JSON and for fields that start with an underscore, it should create setters and getters.
Here is an example of the test JSON:
{
"_language":null,
"_country":null
}
Below is the function I have written:
function jsonToObject(json){
return JSON.parse(json,function(key,value){
if (value && typeof value === 'object') {
return (function(value){
var replacement = {};
for (var k in value) {
if (Object.hasOwnProperty.call(value, k)) {
//if this is private field
if (k.lastIndexOf("_", 0) === 0){
replacement[k]=value[k];
var name=k.substring(1);
var getName="get"+name.charAt(0).toUpperCase() + name.slice(1);
replacement.constructor.prototype[getName]=function(){
return this[k];
};
var setName="set"+name.charAt(0).toUpperCase() + name.slice(1);
replacement.constructor.prototype[setName]=function(newValue){
this[k]=newValue;
};
//if this is public field
}else{
replacement[k]=value[k];
}
}
}
return replacement;
}(value));
}
return value;
});
}
This is how I tested it:
var test1=jsonToObject(data);
test1.setLanguage("11");
console.log("Point A:"+test1.getLanguage());//ouput 11
var test2=jsonToObject(data);
test2.setLanguage("22");
console.log("Point B:"+test2.getLanguage())//output 22
console.log("Point C:"+test1.getLanguage());//output function (a){this[c]=a}
console.log("Point D:"+test2.getLanguage())//output 22
The issue arises at point C - the expected output should be 11. However, it is currently showing a function...(note: this code has been optimized hence looking obfuscated). Where did I go wrong?