了解 JavaScript 函数作用域 [英] Understanding JavaScript function scoping

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

问题描述

下面的代码是 JavaScript 代码.我正在尝试了解 JavaScript 中的函数范围,并在 此处 上关注文章.我正在复制下面的代码 -

The code below is JavaScript code. I am trying to understand function scope in JavaScript and following the article over here. I am reproducing the code below -

var cow = "purple"; // just a random cow

var f = function (x) {
    var r = 0;
    cow = "glue";
    if (x > 3) {
        var cow = 1; // a local variable
        r = 7;
    }
    return r;
};

var z = f(2);
alert(cow); // returns purple

我不太明白为什么会提示字符串purple".cow = "glue"; 行应该将 cow 变量的值设置为glue".如果我删除 if 块,然后在最后一条语句中 alert cow ,我会看到字符串glue"被警告了.

I don't quite understand why the string "purple" is alerted. The line cow = "glue"; should set the value of the cow variable to "glue". If I remove the if block, and then alert cow in the last statement, I see that the string "glue" is alerted.

当调用 f(2) 时,没有输入 if 代码块,其中的任何内容都没有被执行,为什么我看到不同的结果?即为什么最后一条语句中的 alerting cow 现在返回字符串purple"?

When f(2) is called, the if code block is not entered and nothing in it gets executed, so why do I see different results ? i.e why does alerting cow in the last statement return the string "purple" now ?

推荐答案

函数内的变量声明总是被提升到顶部.所以你的代码实际上是:

Variable declarations inside functions are always hoisted to the top. So your code is actually:

var f = function (x) {
    var cow, r;
    r = 0;
    cow = "glue";
    if (x > 3) {
        cow = 1; // a local variable
        r = 7;
    }
    return r;
};

在您总是分配给local cow 的函数中,从不分配给全局.

Inside the function you're always assigning to the local cow, never the global.

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

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