简体   繁体   English

多<script> tags each with its own scope

[英]Multiple <script> tags each with its own scope

I need to programmatically generate multiple <script> tags, and each one is nearly the same except for a parameter which is different. 我需要以编程方式生成多个<script>标记,每个标记几乎相同,除了参数不同。 So for example: 因此,例如:

<script>
    function foo() { console.log('1'); }
    /* lots of very complicated code which calls foo() */
</script>

<script>
    function foo() { console.log('2'); }
    /* lots of very complicated code which calls foo() */
</script>

In this example the first script has a parameter value of '1' so its generated code prints '1' to the console, while the second script has a parameter value of '2'. 在此示例中,第一个脚本的参数值为“ 1”,因此其生成的代码向控制台输出“ 1”,而第二个脚本的参数值为“ 2”。

I know this question so far will offend many good programmers' sensibilities. 我知道到目前为止,这个问题会冒犯许多优秀的程序员。 It's of course greatly simplified and I need to do it this way for reasons beyond the scope of this question. 当然,它已经大大简化了,出于超出该问题范围的原因,我需要这样做。

As I understand it, these <script> tags will share the global scope, so their foo implementations will conflict. 据我了解,这些<script>标记将共享全局范围,因此它们的foo实现将发生冲突。 One fix would be to name them separately, eg foo1 and foo2 . 一种解决方法是分别命名它们,例如foo1foo2 In reality I have many such functions and I'm wondering if there's a better way. 实际上,我有很多这样的功能,我想知道是否有更好的方法。

Is there a good way to enclose each <script> tag in its own scope so that the foo implementations don't conflict? 有没有一种好的方法可以将每个<script>标记括在自己的范围内,以使foo实现不会冲突? I'd prefer to do this without any separate libraries or preprocessing, etc - just with native JavaScript. 我更愿意在没有任何单独的库或预处理等的情况下执行此操作-仅使用本机JavaScript。

I think the only way to do what you want to do is to wrap your code in a self executing function 我认为要做您想做的唯一方法是将代码包装在一个自执行函数中

<script>
(function () {
    function foo() { console.log('1'); }
    /* lots of very complicated code which calls foo() */
})();
</script>

<script>
(function () {
    function foo() { console.log('2'); }
    /* lots of very complicated code which calls foo() */
})();
</script>

If you do this in both instances, then it should have the desired effect. 如果您在两种情况下都执行此操作,则它应具有预期的效果。 It also has the option of having both fragments in the same script tag if that is an option. 如果可以的话,还可以选择将两个片段都放在同一个脚本标签中。

If you problem is more complex and for some reason you want to separate the namespace you can create objects. 如果问题更复杂,并且由于某种原因想要分离名称空间,则可以创建对象。

<script>
var scope1 = (function (){
  return{
    foo: function () {console.log('1');}
  }
})();
</script>

<script>
var scope2 = (function (){
  return{
    foo: function () {console.log('2');}
  }
})();
</script>

Then (using in global scope): 然后(在全局范围内使用):

scope1.foo(); //prints 1
scope2.foo(); //prints 2

I don't know all aspects of your problem, hope you find the best solution :) 我不知道您问题的所有方面,希望您找到最佳解决方案:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM