0

i have a text replacing function below,

function msgConstructor(type, language, withUserName, userName) {
    var txtAndPayloadType = {}
    switch (language) {
        case Enums.DeviceLanguages.tr:
            txtAndPayloadType = Dictionary.tr.notifications[type]
            break;
        case Enums.DeviceLanguages.en:
        default:
            txtAndPayloadType = Dictionary.en.notifications[type]
            break;
    }
    txtAndPayloadType.text = txtAndPayloadType.text.replace('[userName]', userName).replace('[withUserName]', withUserName)
    return txtAndPayloadType;
}

I am getting the value from Dictionary to a seperate var but somehow .replace call on it's text effects the value in Dictionary. I think this has something to do with prototype level. How can i really copy the value from Dictionary to a new var?

garenyondem
  • 541
  • 9
  • 24
  • 1
    no, it's because `txtAndPayloadType` is the object from your dictionary, no copy. It's the exact same object, where you assign a new value to the `text`-property – Thomas Apr 20 '16 at 09:32

1 Answers1

2

When you create an object like so:

var a = { a: 1 };
var b = a;

a only references b. No matter if you then change a property in a or b, it's the same object you're updating.

b.a = 2;
console.log(a.a);     // Outputs 2
console.log(b.a);     // Outputs 2
console.log(a === b); // Outputs true

It doesn't work like this for strings:

var a = "a";
var b = a;
b = "b";
console.log(a);       // Outputs "a"
console.log(b);       // Outputs "b"
console.log(a === b); // Outputs false

What you could do, is only copy the text property, which contains a string:

var newText;
switch (language) {
    case Enums.DeviceLanguages.tr:
        newText = Dictionary.tr.notifications[type].text;
        break;
    case Enums.DeviceLanguages.en:
    default:
        newText = Dictionary.en.notifications[type].text;
        break;
}
return {
  text: newText
    .replace('[userName]', userName)
    .replace('[withUserName]', withUserName)
};
user3297291
  • 22,592
  • 4
  • 29
  • 45