我正在学习 Udemy 上的 JS 课程,老师在解释时展示了该代码片段文档:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="start">Start</div>
<ul>
<li>Element 1</li>
<li>Element 2</li>
</ul>
<button onclick="one()">Click!</button>
<button onclick="two()">Replace!</button>
<script>
function one() {
**x** = document.createElement("p");
x.innerHTML = 'Start Four';
document.getElementById('start').appendChild(x);
}
function two() {
y = document.createElement('p');
y.innerHTML = 'Start Five';
document.getElementById('start').replaceChild(y, **x**);
}
</script>
</html>
根据我的理解,函数 one() 中的变量 x 应该具有函数块作用域,我实际上无法理解为什么当 x 作为函数 Two() 中的参数传递时浏览器不会给出任何错误。
我预计浏览器会抛出错误
由于 x 没有用 var、let 或 const 显式声明,因此它成为全局变量(全局对象的属性,在浏览器中是 window 对象)。因此,它可以在整个全局范围内(函数之外)访问。注意:我仍在学习,所以我可能是错的:D GL