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

查看:30
本文介绍了在 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?

推荐答案

这是 JavaScript 引擎使用的一种技术,称为 提升.解析器将在运行之前通读整个函数,并且任何变量声明(即使用 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.

...

我.调用 env 的 CreateMutableBinding 具体方法,传递 dnconfigurableBindings 作为参数.

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

二.调用 env 的 SetMutableBinding 具体方法,传递 dnundefinedstrict 作为参数.

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] 之类的声明.

Before you run a function, look through the function's source code for declarations like 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天全站免登陆