方法范围

发布于 2025-02-13 19:22:02 字数 273 浏览 0 评论 0原文

假设我是代码:

let btn = document.querySelector("button");
btn.addEventListener("click",() => console.log(btn.textContent));

有人可以解释为什么可以存储对DOM节点的引用的BTN变量可以传递给AddEventListener方法的回调函数的内部?我以为这是不范围的,但我看到代码运行没有问题。

我是JS的新手,所以请不要粗鲁的ahaha。

let's say I code:

let btn = document.querySelector("button");
btn.addEventListener("click",() => console.log(btn.textContent));

Can somebody explain why the btn variable, that is storing a reference to a DOM node, can be accessed inside of the callback function passed to the addEventListener method? I thought that it was out of scope but I saw that the code runs without problems.

I'm new to JS so please don't be rude ahaha.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡淡绿茶香 2025-02-20 19:22:02

示波器中出现的任何代码( innine )(是否由函数,块等定义)都可以访问范围( ofert )中的任何变量,其中< em>内部范围是创建的noreferrer“>阴影。

Any code that appears in a scope (inner) (be it defined by a function, block, etc) has access to any variable in the scope (outer) where the inner scope was created unless that variable is shadowed.

初见 2025-02-20 19:22:02

因为您的变量是在全局范围中创建的。 还有更多信息。

Because your variable is created in the global scope. There more information.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文