javascript 无法获取此JS脚本中var的作用域如何工作[重复]

slhcrj9b  于 10个月前  发布在  Java
关注(0)|答案(1)|浏览(47)

此问题在此处已有答案

What is the purpose of the var keyword and when should I use it (or omit it)?(19回答)
昨天关门了。
我正在Udemy上学习JS课程,老师在解释 document 时展示了代码片段:

<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>

字符串
根据我对function one()中的变量x应该有一个函数块作用域的理解,我实际上无法理解为什么当x作为function two()中的参数传递时,浏览器不会给予任何错误。
我预计浏览器会抛出错误

sczxawaw

sczxawaw1#

由于x没有用var、let或const显式声明,因此它成为一个全局变量(全局对象的属性,在浏览器中是窗口对象)。因此,它可以在整个全局范围内访问(在函数外部)。注:我还在学习,所以我可能是错的:D GL

相关问题