简体   繁体   English

有关var声明的JavaScript行为说明

[英]JavaScript behavior explanation regarding a var declaration

I have the following code: 我有以下代码:

"use strict";

function isDefined(variable)
{
    return (typeof (window[variable]) === "undefined") ? false : true;
} 

try
{
    isDefined(isTrue);
}
catch (ex)
{
    var isTrue = false;
}

isTrue = true;

Can someone please explain to me why when I remove the keyword 'var' I get an exception thrown but when it is there it treats it like undefined? 有人可以向我解释为什么我删除关键字“ var”时会引发异常,但是当异常出现时却将其视为未定义?

When running in strict mode, you aren't allow to access variables that aren't previously declared. 在严格模式下运行时,不允许访问以前未声明的变量。 So, isTrue must be declared before you can access it. 因此,必须先声明isTrue才能访问它。 Thus, if you remove the var in front of it and it isn't declared anywhere else, that will be an error. 因此,如果您删除了它前面的var ,并且未在其他任何地方声明它,那将是一个错误。

Quoting from the MDN page on strict mode : MDN页面上以严格模式引用:

First, strict mode makes it impossible to accidentally create global variables. 首先,严格模式使得不可能意外创建全局变量。 In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). 在普通的JavaScript中,迷惑分配中的变量会在全局对象上创建一个新属性,并继续“起作用”(尽管将来可能会失败:在现代JavaScript中可能)。 Assignments which would accidentally create global variables instead throw in strict mode: 会意外创建全局变量的赋值会改为以严格模式抛出:

The part of your question about undefined is a little more complicated. 您的关于undefined的问题部分要复杂一些。 Because of variable hoisting where a variable declaration is hoisted by the compiler to the top of the scope it's declared in, your code with the var statement is equivalent to this: 由于变量提升,编译器将变量声明提升到声明的作用域的顶部,因此带有var语句的代码与此等效:

var isTrue;
try
{
    isDefined(isTrue);
}
catch (ex)
{
    isTrue = false;
}

isTrue = true;

Thus, when you call isDefined(isTrue) , the value of isTrue is undefined . 因此,当你调用isDefined(isTrue) ,价值isTrueundefined It's been declared, but not initialized, therefore it's value is undefined . 它已声明,但尚未初始化,因此其值是undefined When you don't have the var statement, any reference to isTrue in strict mode is an error since it hasn't been declared yet. 当您没有var语句时,在严格模式下对isTrue任何引用都是错误的,因为尚未声明它。

If you just want to know if a variable has a value yet, you can simply do this: 如果您只想知道变量是否还具有值,则可以执行以下操作:

if (typeof isTrue != "undefined") {
    // whatever code here when it is defined
}

Or, if you just want to make sure it has a value if it hasn't already been initialized, you can do this: 或者,如果您只是想确保它具有尚未初始化的值,则可以执行以下操作:

if (typeof isTrue == "undefined") {
    var isTrue = false;
}

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

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