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?
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)
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.