WebDevelopment
Readle code with the help of extending prototypes
1 min read
On this page
In this article we will see how we write more readable code with the help pf extending prototypes.
#Lets take an example of formatting the text in various languages.
#Our UI code without refactoring:-
JS
const header = formatMessage({ id: "config.header"})JS
const addNewProfile = formatMessage({ id: "config.addNewProfile"})In our config file:-
JS
"config.header": "Mustard Market",JS
"config.addNewProfile": "Add new profile"#We can do something like this to refactor repeating formatMessage:-
JS
String.prototype.i18nText = function () {
let key = String(this);
return formatMessage({ id: key });
};Now we can do following in our code:-
JS
const header = "config.header".i18nText()JS
const addNewProfile = "config.addNewProfile".i18nText()Share this post