Javascript <script>之间的环境隔离

This article is categorized as "Garbage" . It should NEVER be appeared in your search engine's results.


为什么这段代码 不会 打印前面的"zero"和"one"?

<!doctype html>
<html>
<head>
<title>HTML Page</title>
</head>
<body>
<script>
    varname="zero";
    console.log(varname);
    var varname="one";
    console.log(varname);
    let varname="two";
    console.log(varname);
    let varname="three";
    console.log(varname);
</script>
</body>
</html>

但是下面的代码起码会打印出"test":

<!doctype html>
<html>
<head>
<title>HTML Page</title>
</head>
<body>
<script>console.log('test');</script>
<script>
    varname="zero";
    console.log(varname);
    var varname="one";
    console.log(varname);
    let varname="two";
    console.log(varname);
    let varname="three";
    console.log(varname);
</script>
</body>
</html>

另一个例子:

首先我们知道有 var hoist 

<!doctype html>
<html>
<head>
<title>HTML Page</title>
</head>
<body>
<script>
console.log(varname); // 会打印出undefined 
var varname="test";
</script>
</body>
</html>

但是,如果我们把 var varname="test"; 拉到另一个<script>里面,就会出错:

<!doctype html>
<html>
<head>
<title>HTML Page</title>
</head>
<body>
<script>
console.log(varname); // Uncaught ReferenceError: varname is not defined
</script>
<script>
var varname="test";
</script>
</body>
</html>

所以可见,<script>之间虽然能传递变量,但还是存在一定“隔阂” .

而且这个“隔阂”有的时候还比想象中的大,比如:

<!doctype html>
<html>
<head>
<title>HTML Page</title>
</head>
<body>
<script>
    let name="zero";
    console.log(name);
</script>
<script>
    let name="one";
    console.log(name);
</script>
</body>
</html>

这段代码会报错,因为重复声明了let类型的变量。但let明明是作用于block,怎么还会跨<script>影响呢?

js,很神奇吧?


 Last Modified in 2023-03-26 

Leave a Comment Anonymous comment is allowed / 允许匿名评论