Javascript 使用未声明变量的函数

Javascript function working with undeclared variable

好的,下面只是让导航在滚动时缩小,但注意到了一些东西。即使我在应该是 mainNav.classList 的时候放了 nav.classList,它仍然有效。然后我登录了控制台,nav 和 mainNav return 相同,即使没有声明 nav。我的 HTML 中的每个 ID 都会发生这种情况,所以如果我只输入没有 getElementById 的 ID 名称,它仍然会注销该节点。我对为什么这样做有点困惑。这是 ES6 的新功能吗?

var mainNav = document.getElementById('nav'); //The whole navigation

window.addEventListener('scroll', function(){
  var scroll = window.pageYOffset | document.body.scrollTop;

  if(scroll < 100){
    nav.classList.remove('nav-shrink');
  } else {
    nav.classList.add('nav-shrink');
  }
});

这不是 ES6 特有的。如果您有一个带有 ID 的 DOM 元素,并将该 ID 用作变量名(未在其他任何地方声明),您将获得 DOM 元素:

演示

console.log(hello);
<div id="hello"></div>