var a = something和window.a = someting有什么区别?

时间:2018-10-04 00:52:48

标签: javascript variables global-variables global-object

我是JavaScript世界的新手,对全局对象(通常是窗口)了解很多,并且知道它只是一个对象,就像我将创建并创建的任何对象一样,我对此感到困惑与let不同的是 var 在全局对象中设置属性

之后 window.a =某物(类似于任何对象)和var a =某物之间是否有区别?

3 个答案:

答案 0 :(得分:2)

在全局上下文中,使用var与分配给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声明的作用域是当前执行上下文。在全局范围内,这与分配给window并无不同,但是在函数内,当函数返回时,var将消失。

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


答案 1 :(得分:0)

如果要将变量window.a =设置为全局变量,请使用a。这意味着任何JS代码都可以访问此变量。 var a =是声明变量的常用方法。在这种情况下,只能在其容器内访问该变量。

答案 2 :(得分:0)

不是,除了Node.js中的情况,其中a = 5var a = 5(以及letconst)不会将值分配给{{1} }。您必须明确地说出global.a

相关问题