Below there's a function that returns the string depending on a current language, for example if the language is "it"
var currLang = "it";
var language = (function () {
/*this.uppercase = function(){
// the following is more like a pseudo since makes no sense:
return this.toUpperCase(); // I mean, it's wrong... I know :(
};*/
return {
it : {
hi : "ciao"
},
es : {
hi : "ola"
}
}[ currLang ];
})();
console.log( language.hi ); // ciao
console.log( language.hi.toUpperCase() ); // CIAO
Above I'm happy to use it like it is, chaining the JS's vanilla String prototype toUpperCase, but I was just wondering:
how to chain a method we created... like .toUpperCase or a custom one like .toFirstUppercase() ? For example:
language.hi.toFirstUppercase()
but keeping our toFirstUppercase inside the language function?
My problem is that language.hi already returns a string, I know that .toUpperCase() operates on the object "String".toUpperCase() but how to make a custom method inside my app that will help to achieve the same?
Please, if the question is not clear I'd like to improve it so let me know! Thx for any suggestion
Use prototypes and add a toFirstUpperCase method to the String.prototype object. This will instantiate an instance of the toFirstUpperCase closure function for every instance of String:
var currLang = "it";
var language = (function () {
/*this.uppercase = function(){
// the following is more like a pseudo since makes no sense:
return this.toUpperCase(); // I mean, it's wrong... I know :(
};*/
return {
it : {
hi : "ciao"
},
es : {
hi : "ola"
}
}[ currLang ];
})();
String.prototype.toFirstUpperCase = function()
{
return this[0].toUpperCase() + this.slice(1, this.length);
}
console.log( language.hi ); // ciao
console.log( language.hi.toUpperCase() ); // CIAO
console.log( language.hi.toFirstUpperCase() ); // Ciao
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With