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

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

问题描述

JavaScript中的 var 关键字导致变量存储在本地作用域中。没有 var 变量属于全局范围。关于功能呢?很明显,当函数被声明为变量时发生了什么

  var foo = function(){...} 

但是什么范围

  function foo(){...} 

属于?



编辑:
我意识到我没有提出正确的问题作为跟进。在最外面的嵌套中,上面两个声明和下面的声明有什么不同?

  foo = function(){。 ..} 


解决方案

它属于 current 范围,始终。例如:

  //全局范围

// foo是一个全局函数
函数foo(){

// bar是foo的本地
函数bar(){

}

}

关于第二个问题,这个:

  foo = function(){...} 

是一个匿名函数表达式分配给一个全局变量(除非你运行的是严格模式,那么 foo 将是未定义的)。与函数foo(){} 之间的区别在于后者是一个函数声明(与变量声明,它被分配了一个匿名函数表达式)。

您可能对这篇关于函数声明和函数表达式的优秀文章感兴趣:命名的函数表达式被解密了。


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() {...}

but what scope does

function foo() {...} 

belong to?

EDIT: 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() {...}

解决方案

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() {...}

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天全站免登陆