在JavaScript中在函数体顶部声明变量的好处

在JavaScript中在函数体顶部声明变量的好处

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

问题描述

我正在阅读Douglas Crockford的书。他正在讨论范围,并说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:

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

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中在函数体顶部声明变量的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:55