javascript - var a = something 和 window.a = someting 之间有什么区别吗?
问题描述
我是 JavaScript 世界的新手,在我对全局对象(通常是 window)了解很多并且知道它只是一个对象,就像我要创建的任何对象一样,并且var在全局对象中设置属性不同于 let
之后 window.a = something (就像在任何对象中一样)和 var a = something之间有什么区别吗?
解决方案
在全球范围内,使用var
vs 赋值window
确实非常相似。但是,是的,存在许多差异。以下是我能想到的几个:
var
声明是提升的,这意味着您可以在var
声明变量之前使用声明的变量。另一方面,尝试window
在分配发生之前使用分配给的东西会产生ReferenceError
:
// This is okay. The variable declaration is hoisted, so you can use it before
// it's been declared (although it won't be assigned its value until later).
console.log(a);
var a = "hello world";
// On the other hand, without var, this creates an error.
console.log(a);
window.a = "hello world";
- 声明的变量
var
不能从全局对象中删除,但window
可以删除简单的赋值:
var a = "hello world";
console.log(a);
delete window.a; // Does nothing for `var`.
console.log(a);
window.a = "hello world";
console.log(a);
delete window.a; // This will delete it, further access creates a ReferenceError.
console.log(a);
- 而且,当然,
var
声明的范围仅限于当前执行上下文。在全局范围内, this 与分配 to 没有区别window
,但在函数内, avar
将在函数返回时消失。
function foo() {
var a = "hello world";
console.log(a);
}
foo();
console.log(a); // ReferenceError
function foo() {
window.a = "hello world";
console.log(a);
}
foo();
console.log(a); // still exists here
推荐阅读
- java - Java Watch Service 无法监视层次结构中定义为 UNC 路径的超过 50-60 个文件夹
- r - Viridis 和 ggplot2/ggmarginal
- javascript - 使用 kafka-node 创建的消费者和生产者无法连接到 kafka 的工作实例
- google-chrome - Chrome - 几个小时后图像从缓存存储中消失
- python - 如何将变量打印为字符串而不是计数?
- angular - mat-selection-list 有一个对象,有可能吗?
- django - 由于添加简单视频,Django不断收到104连接重置,无法转发视频
- javascript - 我应该使用 JQuery 对话框来显示/提交表单元素吗?
- android - Dokka 失败:com.intellij.psi.impl.source.PsiClassImpl 无法转换为 com.intellij.psi.PsiJavaFile
- java - 为什么 Java8 Stream.min() 和 max() 将比较器作为输入?