javascript 将字符串作为函数调用
我在 javascript 中创建了一个如下所示的 i18n 对象来管理我的 javascript 文件中的语言,
i18n = {
currentCulture: 'pt_PT',
pt_PT : {
message_key : "text in portuguese"
},
en_US: {
message_key : "text in english",
},
/**
* translate
*/
__ : function(key,culture){
return this.culture.key;
},
/**
* returns the active user culture
*/
getUserCulture : function(){
return this.currentCulture;
},
/**
* sets the current culture
*/
setCulture : function(culture){
this.currentCulture = culture;
}
}
我需要根据翻译函数的键和区域性参数返回正确的消息。 问题在于,在 return this.culture.key; 行中,javascript 试图在 i18n 对象中找到“文化”属性。 我怎样才能让它调用,例如 this.pt_PT.message_key?
感谢您的帮助。
感谢所有发布解决方案的人。我只能接受一个答案,所以我接受第一个。
I have made an i18n object in javascript like the following to manage the languages in my javascript files
i18n = {
currentCulture: 'pt_PT',
pt_PT : {
message_key : "text in portuguese"
},
en_US: {
message_key : "text in english",
},
/**
* translate
*/
__ : function(key,culture){
return this.culture.key;
},
/**
* returns the active user culture
*/
getUserCulture : function(){
return this.currentCulture;
},
/**
* sets the current culture
*/
setCulture : function(culture){
this.currentCulture = culture;
}
}
I need to return the correct message based on the key and culture params of the translate function.
The problem is that in the line return this.culture.key; javascript is trying to find a "culture" propriety in the i18n object.
How can i make it call, for example this.pt_PT.message_key?
Thanks for your help.
Thanks everyone who posted the solution. I can only accepted one anwser so i accept the first one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用括号表示法。假设
culture
为'pt_PT'
,key
为'message_key'
:Use bracket notation. Assuming
culture
is'pt_PT'
andkey
is'message_key'
:替换:
为:
Replace:
with:
Javascript 对象是关联数组,您可以使用数组语法来查找属性:
返回这个[文化][键];
Javascript objects are associative arrays, and you can use array syntax to look up properties:
return this[culture][key];