我希望能够从我的javascript代码中的任何地方访问javascript中定义的全局字符串列表。
例如,我想定义一个这样的脚本:
<script type="text/javascript">
function translations()
{
this.mytranslation = "Test translation";
this.mytranslation2 = "Test translation 2";
this.mytranslation3 = "Test translation 3";
}
function messages()
{
this.mymessage = "Test message";
this.message2 = "Test message 2";
}
</script>
上面的代码不起作用,它只是在这里展示我想要的东西。
我希望能够简单地通过以下方式调用它:
alert(translations.mytranslation);
和
alert(messages.message2);
从所有其他脚本(只要第一个脚本当然包括在内)
我想要一些适用于Internet Explorer 11(没有实际的类支持)及以上的东西。
谢谢你的建议
更好地使用全局对象而不是函数
translations.mytranslation
.SO对象var translations = {
mytranslation : "Test translation",
mytranslation2 : "Test translation 2",
mytranslation3 : "Test translation 3",
}
console.log(translations.mytranslation)
你可以试试这个constructor
方法:
function translations() {
this.mytranslation = "Test translation";
this.mytranslation2 = "Test translation 2";
this.mytranslation3 = "Test translation 3";
}
function messages() {
this.mymessage = "Test message";
this.message2 = "Test message 2";
}
alert(new translations().mytranslation);
alert(new messages().message2);
你可以从函数返回'this',即
function translations()
{
this.mytranslation = "Test translation";
this.mytranslation2 = "Test translation 2";
this.mytranslation3 = "Test translation 3";
return this;
}
const mytrans = translations();
console.log(mytrans.mytranslation2);
您需要将返回的对象存储在合理的位置。