跨脚本标签提升变量声明? [英] Hoisting variable declarations across script tags?

查看:63
本文介绍了跨脚本标签提升变量声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下代码插入到html文件中:

I have the following code inserted into a html file:

<script>
	console.log(myVar);
	var myVar = 1;
</script>

打开此之后在浏览器中的html页面,myVar的值将是未定义的。
据我所知,这是javascript中的正常行为,因为它首先将
设置为内存空间,然后执行代码。

After opening this html page in a browser the value of myVar will be undefined. As far as I understood this is a normal behavior in javascript as first it sets the memory space and then it executes the code.

现在奇怪的部分是如果我们在同一个html页面中这样拆分:

Now the weird part is if we split this like this for the same html page:

<script>
	console.log(myVar);
</script>

<script>
	var myVar = 1;
</script>

结果将是是:未捕获的ReferenceError:myVar未定义

the result will be: Uncaught ReferenceError: myVar is not defined

为什么?

这不是关于变量的范围,它是关于吊装,似乎吊装仅在javascript块内,并且不适用于其他javascript块中的整个加载页面。这里的例子相同:

This is not about variable's scope, it is about hoisting and it seems that hoisting is only inside a javascript block and not available for the whole loaded page in other javascript blocks. The same example here:

<script>
	myFunc();

  function myFunc() {
		console.log('Hello!');
	}
</script>

VS

<script>
	myFunc();
</script>


<script>
	function myFunc() {
		console.log('Hello!');
	}
</script>

推荐答案

在上面的代码中,首先呈现带有 console.log(myVar)< script> 系统在全局和本地范围内查找 myVar 变量。因为,直到此时它才会找到变量,未捕获的ReferenceError:未定义myVar 错误为 var myVar = 1; 在下一个< script> 块中呈现。

In the above code the <script> with console.log(myVar) is rendered first and the system looks for the myVar variable in the global and local scope. Since, the variable is not found till this point it raises, Uncaught ReferenceError: myVar is not defined error as var myVar = 1; is rendered in the next <script> block.

<script>
  console.log(myVar);
</script>

<script>
  var myVar = 1;
</script>

但是当你将< script> 块的顺序更改为类似下面的内容然后它将起作用

But when you change the order of the <script> blocks to something like below then it will work

<script>
  var myVar = 1;
</script>

<script>
   console.log(myVar);
</script>

这篇关于跨脚本标签提升变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆