我想将语言变量从我的 html 库中分离出来,但我不确定最好的方法是什么。
目前我有这样的东西;
function putAlertA() {
alert('This is alert a');
}
function putAlertB() {
alert('This is alert b');
}
function setAlerts() {
putAlertA();
putAlertB();
}
现在我想将字符串与函数分开:
解决方案 A
function putAlertA() {
var strings = getLanguageVars();
alert(strings[0]);
}
function putAlertB() {
var strings = getLanguageVars();
alert(strings[1]);
}
function setAlerts() {
putAlertA();
putAlertB();
}
function getLanguageVars() {
var strings = new Array();
strings[0] = "This is alert a";
strings[1] = "This is alert b";
return strings;
}
方案B
function putAlertA(strings) {
alert(strings[0]);
}
function putAlertB(strings) {
alert(strings[1]);
}
function setAlerts() {
var strings = getLanguageVars();
putAlertA(strings);
putAlertB(strings);
}
function getLanguageVars() {
var strings = new Array();
strings[0] = "This is alert a";
strings[1] = "This is alert b";
return strings;
}
方案 C
function putAlertA() {
var strings = window.strings;
alert(strings[0]);
}
function putAlertB() {
var strings = window.strings;
alert(strings[1]);
}
function setAlerts() {
putAlertA();
putAlertB();
}
window.strings = new Array();
strings[0] = "This is alert a";
strings[1] = "This is alert b";
我认为解决方案 C 是最好的,因为我认为解决方案 A 和 B 会在内存消耗方面产生过多的开销,而且看起来不太合逻辑,因为语言数组是一个全局变量。然而,我对使用 window.
有点犹豫。不确定如何执行此操作是正确的方法。也许有更好的方法如何做到这一点?我正在使用 jQuery
最佳答案
我的偏好是静态对象,例如:
l10n = {
strings: [
'alert_a': 'this is alert a',
'alert_b': 'this is alert b'
],
translate: function(key) {
return this.strings[key];
}
}
调用:
alert(l10n.translate('alert_a');
这种方法的好处是它更容易扩展,例如,通过引入参数化的本地化字符串,例如:
"Hello :name:"
调用:
l10n.translate('key', {
name: 'world'
})
// "Hello world"
关于javascript - 解析js html库中的字符串(语言字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15052521/