javascript 函数声明的范围 [英] javascript scope of function declarations

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

问题描述

javascript 中的 var 关键字导致将变量存储在本地范围内.没有 var 的变量属于全局范围.函数呢?很明显当函数被声明为变量时会发生什么

The var keyword in javascript causes a variable to be stored in the local scope. Without var variables belong to the global scope. What about functions? It's clear what happens when functions are declared like variables

var foo = function() {...}

但是作用域是什么

function foo() {...} 

属于?

我意识到我没有问正确的问题,所以作为跟进.在最外层的嵌套中,上面两个声明和下面的声明有区别吗?

I realized I didn't ask quite the right question so as a follow up. In the outer most nesting is there a difference between the above two declarations and the following declaration?

foo = function() {...}

推荐答案

它始终属于 current 范围.例如:

It belongs to the current scope, always. For example:

// global scope

// foo is a global function
function foo() {

    // bar is local to foo
    function bar() {

    }

}

关于你的第二个问题,这个:

Regarding your second question, this:

foo = function() {...}

是分配给全局变量的匿名函数表达式(除非您在严格模式下运行,否则 foo 将是未定义的).它与 function foo() {} 的区别在于后者是一个函数声明(相对于一个变量声明,它被分配了一个匿名函数表达式).

is an anonymous function expression assigned to a global variable (unless you're running is strict mode, then foo would be undefined). The difference between that and function foo() {} is that the latter is a function declaration (versus a variable declaration, which is assigned an anonymous function expression).

您可能对这篇关于函数声明和函数表达式的优秀文章感兴趣:命名函数表达式揭秘.

You might be interested in this excellent article about function declarations and function expressions: Named function expressions demystified.

这篇关于javascript 函数声明的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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