JavaScript中的变量定义和声明之间有什么区别? [英] What's the difference between variable definition and declaration in JavaScript?

查看:132
本文介绍了JavaScript中的变量定义和声明之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is this a variable definition or declaration? And why?

var x;

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

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

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

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.

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

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

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

如果 ReferenceError 输出会说 y未声明这是有意义的。但我经常读到JS有两个非值: null undefined 。所以 var x 将是一个值 undefined 的定义。

If the ReferenceError output would say y is not declared it would make sense. But often I read that JS has two non-values: null and undefined. So var x would be a definition with the value undefined.

推荐答案

var x 声明因为你没有定义它拥有什么值,但你声明它的存在和内存分配的需要。

var x is a declaration because you are not defining what value it holds but you are declaring its existence and the need for memory allocation.

var x = 1 既是声明又是定义,但用 x 分隔声明在开头,其定义来自指定的行(变量赋值发生在内联)。

var x = 1 is both declaration and definition but are separated with x being declared in the beginning while its definition comes at the line specified (variable assignments happen inline).

我看到你已经理解了提升的概念,但对于那些没有的人来说,Javascript采用了每一个变量和函数声明并将其置于顶部(相应范围)然后按顺序向下分配它们。

I see that you already understand the concept of hoisting but 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.

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

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

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

这篇关于JavaScript中的变量定义和声明之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆