admin管理员组文章数量:1355619
In javascript, What is the difference between function declaration and function expression in terms of scope? function declaration means we are polluting the global space. Is it the same case with function expression?
Function declaration
function sum(){
// logic goes here
}
Function expression
var sum = function(){}
In javascript, What is the difference between function declaration and function expression in terms of scope? function declaration means we are polluting the global space. Is it the same case with function expression?
Function declaration
function sum(){
// logic goes here
}
Function expression
var sum = function(){}
Share
Improve this question
edited Nov 10, 2010 at 5:17
casablanca
70.8k7 gold badges138 silver badges154 bronze badges
asked Nov 10, 2010 at 5:14
CKRCKR
2234 silver badges8 bronze badges
1
- stackoverflow./questions/336859/… and stackoverflow./questions/1013385/… – Phil Commented Nov 10, 2010 at 5:19
2 Answers
Reset to default 10Both are equivalent in terms of scope. A function declared inside another function will not be global. The difference is that you can use a declared function at any time (because it's hoisted before any code is run), a function assigned to a variable as an expression only after you have assigned it.
(function () {
bar(); // works
function bar() { } // is not global
foo(); // doesn't work
var foo = function () { };
})();
As far as polluting the enclosing scope goes, both are equivalent. Note that it is not necessarily the global scope - it is the scope in which the function is declared (local functions are permitted within other functions). In your example, both methods introduce a variable (function object) named sum
into the local scope.
本文标签: javascriptFunction declarationFunction ExpressionScopeStack Overflow
版权声明:本文标题:javascript - Function declaration - Function Expression - Scope - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743965444a2569800.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论