简体   繁体   English

Javascript innerWidth 而不是 window.innerWidth

[英]Javascript innerWidth instead of window.innerWidth

有什么理由我应该使用window.innerWidth而不是innerWidth吗?

window.innerWidth is always a property of the window object, so you're safe as long as a window exists (in other js environments like Node.js it doesn't), while innerWidth refers to the global object only if there isn't already a variable with the same name in the current scope. window.innerWidth始终是 window 对象的一个​​属性,因此只要窗口存在(在其他 js 环境中,例如 Node.js 中不存在),您就是安全的,而仅在不存在时, innerWidth引用全局对象t 在当前作用域中已经是一个同名的变量。

For example例如

// This logs the actual window.innerWidth
console.log(innerWidth);

function something() {
  const innerWidth = 4;

  // This innerWidth will not refer to the global object..
  console.log(innerWidth);
}

// ..so this logs 4
something();

So either you remember all of the window properties so you don't incur in conflicting variable names (not very handy and hard to debug) or you just access the window object explicitly, making the code a little more verbose but also clearer and less error-prone.所以要么你记住所有的window属性,这样你就不会产生冲突的变量名(不是很方便且难以调试),或者你只是显式地访问window对象,使代码更冗长,但也更清晰,错误更少-易于。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM