首页 > 解决方案 > var a = something 和 window.a = someting 之间有什么区别吗?

问题描述

我是 JavaScript 世界的新手,在我对全局对象(通常是 window)了解很多并且知道它只是一个对象,就像我要创建的任何对象一样,并且var在全局对象中设置属性不同于 let

之后 window.a = something (就像在任何对象中一样)和 var a = something之间有什么区别吗?

标签: javascriptvariablesglobal-variablesglobal-object

解决方案


在全球范围内,使用varvs 赋值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



推荐阅读