简体   繁体   English

JS:为什么允许使用和不使用`var`关键字来声明变量?

[英]JS: Why are variables allowed to be declared both with and without the `var` keyword…?

It is possible to declare a javascript variable both with and without the var keyword. 可以使用var关键字和不使用var关键字来声明一个JavaScript变量。

var a = 100; // this works!
    b = 200; // and this does too!

It is also possible to declare a variable without initialisation. 也可以在不初始化的情况下声明变量。

var c;       // this is just as acceptable! 

But then why is the same NOT true for a variable without var, to be declared without initialisation. 但是,为什么对于不带变量的不带变量的变量不进行初始化就不一样呢?

var c; 
    d;       // causes a reference error to occur!

Why? 为什么?

First, what you're seeing is legacy behavior. 首先,您看到的是传统行为。 Assignment to an undeclared symbol traditionally meant, implicitly, that a global symbol should be created (declared) and set to the given value. 分配给未声明的符号在传统上隐含地意味着应创建(声明)全局符号并将其设置为给定值。 Thus 从而

x = 1;

when x has not been declared was taken to be an implicit instantiation of a global symbol. 如果尚未声明x则将其视为全局符号的隐式实例。

The mention of an undeclared symbol, as in: 提及未声明的符号,例如:

x;

is an error because the symbol is undeclared. 错误,因为未声明该符号。

In modern JavaScript, and when "strict" mode is in force because of a 在现代JavaScript中,由于

"use strict";

statement (or because of other influences, as may be the case with Node.js code), the implicit creation of global symbols is also erroneous. 语句(或由于其他影响,例如Node.js代码的情况),全局符号的隐式创建也是错误的。

Generally, implicit global symbol instantiation is considered a bad idea. 通常,隐式全局符号实例化被认为是一个坏主意。 Global symbols in browser JavaScript are quite problematic because the global namespace is so horribly polluted. 浏览器JavaScript中的全局符号存在很大问题,因为全局名称空间受到了严重的污染。 Thankfully, it's easy to wrap code in a function scope to create a "safe space" for symbols without fear of the browser imposing weird global names. 值得庆幸的是,很容易将代码包装在函数作用域中以为符号创建“安全空间”,而不必担心浏览器会使用奇怪的全局名称。

You can do that in non-strict mode 您可以在非严格模式下执行此操作

   var a = 100; // this works!
        b = 200; // and this does too!

for non-strict mode, someVar = someValue, if someVar is not existed, javascript will declare it and assign a someValue to someVar. 对于非严格模式,someVar = someValue,如果someVar不存在,则javascript将对其进行声明,并将someValue分配给someVar。

For that case: 对于这种情况:

var c; 
    d;       // causes a reference error to occur!

line 1: var c; 第1行:var c; --> declare c, it's valid syntax. ->声明c,这是有效的语法。 line 2: d; 第2行:d; --> you access d, but d is underfined --> causes error !!! ->您访问d,但d的定义不足->导致错误! assume d is defined anywhere before that line, so it should NOT cause error!! 假设d在该行之前的任何位置定义,因此它不会引起错误!

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

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