try块中的JavaScript作用域 [英] JavaScript scope in a try block

查看:36
本文介绍了try块中的JavaScript作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我正在尝试执行此JavaScript代码段.假设未声明的var和方法在上面的其他地方声明,并且 something somethingElse 的计算结果为boolean-true.

Say I'm trying to execute this JavaScript snippet. Assume the undeclared vars and methods are declared elsewhere, above, and that something and somethingElse evaluate to boolean-true.

try {
    if(something) {
        var magicVar = -1;
    }

    if(somethingElse) {
        magicFunction(magicVar);
    }
} catch(e) {
    doSomethingWithError(e);
}

我的问题是: magicVar 的范围是什么,可以像我一样将其传递给 magicFunction 吗?

My question is: what is the scope of magicVar and is it okay to pass it into magicFunction as I've done?

推荐答案

JavaScript具有功能范围.这意味着 magicvar 从声明的函数开始一直存在到该函数的结尾,即使该语句从未执行过也是如此.这称为可变吊装.函数声明也会发生同样的事情,这又称为函数提升.

Javascript has function scope. That means that magicvar will exist from the beginning of the function it's declared in all the way to the end of that function, even if that statement doesn't ever execute. This is called variable hoisting. The same thing happens with functions declarations, which in turn is called function hoisting.

如果变量是在全局范围内声明的,则所有内容都将可见.这是在Javascript中将全局变量视为邪恶的部分原因.

If the variable is declared in global scope, it will be visible to everything. This is part of the reason why global variables are considered evil in Javascript.

如果 something 为false,则您的示例会将 undefined 传递给 magicFunction ,因为未分配 magicVar 什么都可以.

Your example will pass undefined into magicFunction if something is false, because magicVar hasn't been assigned to anything.

尽管这在技术上是有效的Javascript,但通常被认为是不良样式,并且不会通过jsLint这样的样式检查器.这样极其不直观的Javascript将会执行而不会出现任何错误

While this is technically valid Javascript, it's generally considered bad style and will not pass style checkers like jsLint. Extremely unintuitive Javascript like this will execute without any error

alert(a); //alerts "undefined"
var a;

POP测验:以下代码是做什么的?

POP QUIZ: What does the following code do?

(function() {
  x = 2;
  var x;
  alert(x);
})();
alert(x);

这篇关于try块中的JavaScript作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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