JavaScript 中的变量定义和声明有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20822022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:23:09  来源:igfitidea点击:

What's the difference between variable definition and declaration in JavaScript?

javascript

提问by cakl

Is this a variable definitionor declaration? And why?

这是变量定义还是声明?为什么?

var x;

var x;

..and is the memory reserved for x after this statement?

..并且是在此语句之后为 x 保留的内存吗?

EDIT: In C extern int x;is a declaration, int x = 5;is a definition. What's the analog in JS? Wikipedia says a declaration allocates memory and the definition assigns a value to this allocated memory.

编辑:在 C 中 externint x;是一个声明,int x = 5;是一个定义。JS 中的模拟是什么?维基百科说声明分配内存,定义为这个分配的内存分配一个值。

SECOND EDIT: I think the explanation of @Deryck sounds great, but there's some output that disagrees with his explanation:

第二次编辑:我认为@Deryck 的解释听起来不错,但有些输出与他的解释不一致:

> var x;
undefined
> x
undefined // now it looks like x is defined to the value undefined
> y
ReferenceError: y is not defined

If the ReferenceErroroutput would say y is not declaredit would make sense. But often I read that JS has two non-values: nulland undefined. So var xwould be a definition with the value undefined.

如果ReferenceError输出会说y is not declared这是有道理的。但我经常读到 JS 有两个非值:nullundefined. 因此,var x将与价值的定义undefined

回答by Deryck

var xis a declarationbecause you are not definingwhat value it holds but you are declaringits existence and the need for memory allocation.

var x是一个声明,因为您没有定义它拥有什么值,而是声明它的存在和内存分配的需要。

var x = 1is both declaration and definition but are separated with xbeing declaredin the beginning while its definitioncomes at the line specified (variable assignments happen inline).

var x = 1既是声明和定义,但与分开x进行申报,而其在一开始定义来在指定的行(变量赋值内嵌发生)。

I see that you already understand the concept of hoistingbut for those that don't, Javascript takes every variable and function declaration and brings it to the top (of its corresponding scope) then trickles down assigning them in order.

我看到你已经理解了hoisting但对于那些没有理解的概念,Javascript 获取每个变量和函数声明并将其带到(其​​相应范围的)顶部,然后按顺序分配给它们。

You seem to know most of this already though. Here's a great resource if you want some advanced, in-depthexploration. Yet I have a feeling you've been there before.

不过,您似乎已经知道其中的大部分内容。如果您想要一些高级、深入的探索这里有一个很好的资源。但我有一种感觉,你以前去过那里。

Javascript Garden

Javascript花园

PS - your analogy between C variable dec/def and JS was spot on. What you read on Wikipedia was correct.

PS - 您在 C 变量 dec/def 和 JS 之间的类比是正确的。你在维基百科上读到的是正确的。

回答by hamid

Declaring a variable is like telling the (javascript) compiler that this token xis something I want to use later. It does point to a location in memory, but it does not yet contain a value. ie. it is undefined

声明一个变量就像是告诉(JavaScript)的编译器,此令牌x是我想要使用。它确实指向内存中的一个位置,但它尚未包含值。IE。它是undefined

var x;

defining it means to give it a value which you can either do it like:

定义它意味着给它一个值,你可以这样做:

x = 10; // defining a variable that was declared previously

or like this:

或者像这样:

var y = 20; // declaring and defining a variable altogether.

http://msdn.microsoft.com/en-us/library/67defydd(v=vs.94).aspxhttp://www.w3schools.com/js/js_variables.asp

http://msdn.microsoft.com/en-us/library/67defydd(v=vs.94).aspx http://www.w3schools.com/js/js_variables.asp

回答by kaizer1v

I will give you a long answer for better explanation.

为了更好的解释,我会给你一个很长的答案。

When the javascript engine is not able to find a particular variable in memory, it will throw an error. To be more specific, when the javascript engine (Execution Context) is not able to "reference" a variable in memory, it will throw a ReferenceError. This is not exactly the same as a Declaration Error, at least in javascript.

当 javascript 引擎无法在内存中找到特定变量时,它会抛出错误。更具体地说,当 javascript 引擎(执行上下文)无法“引用”内存中的变量时,它会抛出一个ReferenceError. 这与声明错误并不完全相同,至少在 javascript 中是这样。

There is a deference between a not definederror and the value undefined.

not defined错误和值之间存在差异undefined

So doing

这样做

var a = undefined;

and

var a;

will both log the same result i.e. undefined. This is because, when you simply do a var a;the javascript engine allocates memory for the variable and automatically sets it's value to undefined, which is different from saying that adoesn't exist at all - in which case it will throw a ReferenceError.

都将记录相同的结果,即undefined. 这是因为,当您简单地执行 a 时var a;,javascript 引擎会为变量分配内存并自动将其值设置为undefined,这与说a根本不存在不同 - 在这种情况下,它将抛出ReferenceError.

Hoisting

吊装

console.log(a);    // undefined
var a = 'something';

will log undefinedbecause, the javascript engine knows there's a variable declaredsomewhere in the code - which means to say that the javascript engine actually does something before it executes the code - one of the thing it does is hoistsvariables. To put it simply, the above code is the same as

会记录,undefined因为 javascript 引擎知道在代码中的某处声明了一个变量——这意味着 javascript 引擎在执行代码之前实际上做了一些事情——它所做的一件事就是提升变量。简单来说,上面的代码和

var a;             // hoisted (declared and defined the value `undefined`)
console.log(a);    // undefined
a = 'something'    // update the defined value to `something`

So, yes, declaration and definition happen together in javascript (automatically - if you don't do it yourself) and the default defined value is undefined.

所以,是的,声明和定义在 javascript 中一起发生(自动 - 如果你自己不这样做)并且默认定义值是undefined.

ES6

ES6

Just an additional note

只是一个额外的说明

const a;

will throw a SyntaxErrorwhere a initializer (definition) is necessary. constis the only time when you need to declare and define manually.

将抛出一个SyntaxError需要初始化程序(定义)的地方。const是唯一需要手动声明和定义的时候。

回答by Apurva Pathak

var x;

This is a variable declaration. In Js if you don't assign any value to variable in declaration. It will get undefinedby default.

这是一个变量声明。在 Js 中,如果您没有在声明中为变量分配任何值。它将undefined默认获得。

var x; // declaring x
console.log(x); // output: undefined

But if you have not even declared the variable in you try to access it. It says that the variable is not defined.

但是,如果您甚至没有在其中声明变量,请尝试访问它。它说变量未定义。

console.log(y);  // Output: ReferenceError: y is not defined

If you need access to objects between JS files, it's good practice to expose one object to the global namespace and declare fields and methods on that object.

如果您需要访问 JS 文件之间的对象,最好将一个对象暴露给全局命名空间并在该对象上声明字段和方法。

File 1:

文件 1:

var myObject;
myObject.myField = "Field!";   

File 2:

文件2:

myObject.prototype.myFunction = function () {
    return this.myField;
};

I have taken from a really good discussion on : Equivalent of C extern declaration in JavaScript

我从一个非常好的讨论中摘取等效于 JavaScript 中的 C extern 声明

https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions

https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions

回答by CRABOLO

var x, y, z;

var x;

var h = 4;

i = 4;

all the above are global variables if placed at the top, (outside any functions)

如果放在顶部,以上所有都是全局变量,(在任何函数之外)

Lets say that the javascript has a function start

假设 javascript 有一个函数 start

function start() {
      x = 5*5;
}

the global variable x is now equal to 25

全局变量 x 现在等于 25

Where as if the var x; was not placed outside of any functions, that variable x would just be local to that function.

哪里好像 var x; 没有放置在任何函数之外,变量 x 只是该函数的局部变量。

回答by Gourav

You declare JavaScript variables with the var keyword: var carname;

使用 var 关键字声明 JavaScript 变量: var carname;

After the declaration, the variable is empty (it has no value).

声明后,变量为空(没有值)。

To assign a value to the variable, use the equal sign var carname="Volvo";

要为变量赋值,请使用等号 var carname="Volvo";

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.

在计算机程序中,变量的声明通常没有值。该值可以是必须计算的内容,也可以是稍后提供的内容,例如用户输入。没有值声明的变量将具有未定义的值。

The variable carname will have the value undefined after the execution of the following statement: var carname;

执行以下语句后,变量 carname 将具有 undefined 值: var carname;

var hoisting

无功吊装

In JavaScript, a variable can be declared after being used.

在 JavaScript 中,变量可以在使用后声明。

 bla = 2
 var bla;
  // ...

  // is implicitly understood as:

 var bla;
 bla = 2;

For that reason, it is recommended to always declare variable at the top of functions. Otherwise, it may lead to confusing cases

因此,建议始终在函数顶部声明变量。否则,可能会导致混乱的情况

When declaring a variable without assigning a value to it, there still needs to be some memory available for it, otherwise you cannot make a reference to the variable later in the program. I don't think it's a noticeable amount of memory being used and won't make a difference.

When declaring a variable without assigning a value to it, there still needs to be some memory available for it, otherwise you cannot make a reference to the variable later in the program. I don't think it's a noticeable amount of memory being used and won't make a difference.

回答by Aneesha Rao

In simple terms,

简单来说,

undefined means valueto the variable is not defined.

undefined 表示变量的未定义。

not defined means the variableitself is not defined.

未定义意味着变量本身未定义。

var x; //value is not defined. So, x //undefined

var x; //value is not defined. So, x //undefined

//y variable is not declared or defined. So, y // y is not defined

//y variable is not declared or defined. So, y // y is not defined