在JavaScript中在函数体顶部声明变量的好处 [英] The benefits of declaring variables at the top of the function body in JavaScript

查看:66
本文介绍了在JavaScript中在函数体顶部声明变量的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Douglas Crockford的书Javascript:The Good Parts 。他正在讨论范围,并说JS没有块范围:

I am reading Douglas Crockford's book "Javascript: The Good Parts". He is talking about scope and saying that JS doesn't have block scope:


在许多现代语言中,建议声明变量在第一个使用点,尽可能晚地
。结果证明是
对Javascript的错误建议,因为它缺少块范围。所以相反,
最好在函数体的顶部
中声明函数中使用的所有变量。

In many modern languages, it is recommended that variables be declared as late as possible, at the first point of use. That turns out to be bad advice for Javascript because it lacks block scope. So instead, it is best to declare all of the variables used in a function at the top of the function body.

但是,我想不出一个很好的例子,为什么这个语句有意义,看到一些验证这个语句的例子真的很好。

However, I couldn't think of a good example why this statement makes sense and it would be really nice to see some examples which verify this statement.

推荐答案

在顶部声明变量有助于避免这样的情况:

Declaring variables at the top helps you avoid situations like this:

function outer() {
  var i = 50;

  function inner() {
    alert(i);
    var i= 30;
  }
  inner();
}

outer();

很多人都希望警报显示 50 ,他们会惊讶地看到 undefined 。那是因为 i 变量是在内部函数中声明的,但是直到<$ c之后它才被初始化$ C>警报。因此它具有完整的功能范围,即使它在初次使用后被声明。

Many people would expect the alert to show 50, and they would be surprised to see undefined. That's because the i variable is declared within the inner function, but it isn't initialized until after the alert. So it has full function scope, even though it's declared after its initial use.

这篇关于在JavaScript中在函数体顶部声明变量的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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