这之所以有效,是因为您的HTML代码中设置了id
属性的元素会自动创建为全局window
对象的属性(在本例中为globalThis
).此行为有时称为"命名元素":
"use strict";
console.log(window.test); // `test` is a named element
console.log(test); // ends up accessing window.test
console.log(globalThis.test); // also same as accessing window.test
<input type="text" id="test" />
上面,仅仅因为我们为文本输入设置了id
/"test"
,它现在就在window
上创建了一个名为test
的全局属性,我们可以访问该属性.虽然这是可行的,但避免以这种方式访问元素,而使用.querySelector()
和.getElementById()
等方法则是considered best practice
在本例中,您使用const
来声明num1
变量,这样num1
变量就不会像省略const
或使用var
那样成为window
(globalThis
)对象上的属性.因此,window
对象上自动添加的num1
属性保持不变,不会被您的变量声明覆盖.这意味着在执行globalThis.num1
操作时,您不是在访问在周围作用域中声明的变量,而是在访问自动添加的窗口属性,该属性是在为元素赋予id时自然获得的(如上面的代码片断所示).这就是为什么您的代码即使在没有const num1
声明的情况下也可以工作:
"use strict";
// const num1 = document.getElementById("number1");
const outp = document.getElementById("output");
function show() {
const num1 = parseFloat(globalThis.num1.value);
outp.innerHTML = num1;
}
<div>
<label for="num1">Number 1</label>
<input type="number" id="num1">
</div>
<button type="button" onclick="show()">Show</button>
<div>Output <label id="output"></label></div>
我的建议是,如果需要在函数中访问外部全局变量,则停止跟踪外部全局变量,以避免所有这些问题.要做到这一点,只需在函数中调用非num1
的变量即可:
"use strict";
const num1 = document.getElementById("num1"); // update to the correct value
const outp = document.getElementById("output");
function show() {
const num1Float = parseFloat(num1.value);
outp.innerText = num1Float; // use innerText or textContnt if the content you're setting is just text, not HTML
}
<div>
<label for="num1">Number 1</label>
<input type="number" id="num1">
</div>
<button type="button" onclick="show()">Show</button>
<div>Output <label id="output"></label></div>