JavaScript block scope vs function - Stack Overflow

Are following snippets exactly equal? If no what is the deference?var x = (function() {... areturn fu

Are following snippets exactly equal? If no what is the deference?

var x = (function() {
    ... //a
    return function(){
        ... //b
    };
})();

vs.

var x;
{
    ... //a
    x = function(){
        ... //b
    };
}

Are following snippets exactly equal? If no what is the deference?

var x = (function() {
    ... //a
    return function(){
        ... //b
    };
})();

vs.

var x;
{
    ... //a
    x = function(){
        ... //b
    };
}
Share Improve this question edited Jan 25, 2016 at 6:56 Ali Shakiba asked Apr 30, 2011 at 11:15 Ali ShakibaAli Shakiba 21.3k18 gold badges65 silver badges90 bronze badges 7
  • @JohnS please don't paste code into the title like that. Post your code into the body. – JohnP Commented Apr 30, 2011 at 11:23
  • @JohnP You are right but your title is too generic, it's like "What's the problem with my code?" – Ali Shakiba Commented Apr 30, 2011 at 11:24
  • @JohnS but that is what you're asking. Pasting the code into the title does not make it readable. Feel free to e up with a better problem statement for your question – JohnP Commented Apr 30, 2011 at 11:25
  • @JohnP Have you seen: stackoverflow./questions/336859/… – Ali Shakiba Commented Apr 30, 2011 at 11:31
  • @JohnS That's 3 years old. I've only been active for a couple of months. Also that question title is much more readable than what you had put up. Like I said before, please do update your question if you have a better title :) It just needs to be clear and readable – JohnP Commented Apr 30, 2011 at 11:37
 |  Show 2 more ments

2 Answers 2

Reset to default 6

There is a major difference: In JavaScript, blocks don't induce a new variable scope. Therefore, you can't define private variables in the // a code block. Compare

var x = (function() {
    var v = 42;
    return function(){
        return v;
    };
})();
// v; would yield ReferenceError: v is not defined, so you need to call x

and

var x;
{
    var v = 42;
    x = function(){
        return v;
    };
}
// v is 42 here, that's not what's intended.

One major difference is that at the time of executing ...//a , x doesn't exist. Now in your case, in both cases it is undefined but generally speaking it's possible to access x variable during ...//a while in the first case it's not.

Otherwise in your circumstances it's pretty same. After all in your case the code is basically refactored into a separate function just like in any other language.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745633170a4637229.html

相关推荐

  • JavaScript block scope vs function - Stack Overflow

    Are following snippets exactly equal? If no what is the deference?var x = (function() {... areturn fu

    22天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信