在javascript中以几个伪造类暴露全局字符串列表的简单方法

问题描述 投票:1回答:3

我希望能够从我的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(没有实际的类支持)及以上的东西。

谢谢你的建议

javascript
3个回答
2
投票

更好地使用全局对象而不是函数

  • 你定义了函数,但你只调用translations.mytranslation.SO对象

var translations  = {
         mytranslation : "Test translation",
         mytranslation2 : "Test translation 2",
         mytranslation3 : "Test translation 3",
    }

    
 console.log(translations.mytranslation)

1
投票

你可以试试这个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);

0
投票

你可以从函数返回'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);

您需要将返回的对象存储在合理的位置。

© www.soinside.com 2019 - 2024. All rights reserved.