在Javascript中,我可以在声明之前使用变量吗? [英] In Javascript, can I use a variable before it is declared?

查看:95
本文介绍了在Javascript中,我可以在声明之前使用变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想,如果我可以在定义之前在JS中使用变量,
如下:

I have been wondering for a while if I can use a variable in JS before it is defined, such as the following:

var country = "USA";
switch (country) {
    case "USA":
        country = i;
    case "blach":
        //not finished yet
}
/*
  put a whole
  bunch more code here
*/
var i = 10;

这有效吗?是允许的吗?如果是这样,它的技术术语是什么?

Is this valid? Is it allowed? And if so, what is the technical term for it?

推荐答案

这是一种名为 吊装 。解析器将在运行之前读取整个函数,并且将执行任何变量声明(即使用 var 关键字),就像它们位于包含范围的顶部一样。所以你的代码表现如下:

This is a technique used by the JavaScript engine called hoisting. The parser will read through the entire function before running it, and any variable declarations (i.e. using the var keyword) will be executed as if they were at the top of the containing scope. So your code behaves like:

var country;
var i;

country = "USA";
switch (country) {
case "USA":
    country = i;
case "blach":
    //not finished yet
}

i = 10;

因此, i 声明的在整个范围内,但其值为 undefined ,直到 i = 10 语句运行。

So, i is declared throughout the entire scope, but its value is undefined until the i = 10 statement runs.

在ECMAScript术语中,当调用函数时,函数的新词法范围在任何函数代码之前构建其 VariableEnvironment 运行。在 ECMAScript 10.5,第8步中:

In ECMAScript terms, when a function is invoked, the function's new lexical scope builds its VariableEnvironment before any of the function's code runs. In ECMAScript 10.5, step 8:


8。对于代码中的每个 VariableDeclaration ... d ,在源文本顺序中执行

8. For each VariableDeclaration... d in code, in source text order do

一个。让 dn 成为d中的标识符。

a. Let dn be the Identifier in d.

...

i。调用 env 的CreateMutableBinding具体方法,将 dn configurableBindings 作为参数传递。

i. Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.

II。调用 env 的SetMutableBinding具体方法传递 dn undefined strict 作为参数。

ii. Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.

这是相当满口的,但基本上它说:

This is quite a mouthful, but basically it says:


在运行函数之前,请查看函数的源代码,以获取声明,例如 var [identifierName]

对于您找到的每个声明,在函数的作用域中创建一个新变量,在声明中使用名称 [identifierName] ,然后将其值设置为 undefined

For each declaration you find, create a new variable in the function's scope with the name [identifierName] used in the declaration and then set its value to undefined

这篇关于在Javascript中,我可以在声明之前使用变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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