JavaScript define and return a variable on one line

前端 未结 3 714
轻奢々
轻奢々 2021-01-25 03:19

In JavaScript, if I want to return a variable but don\'t want to modify it or leak it into the global scope, can I define and return it on one line like this?

re         


        
3条回答
  •  终归单人心
    2021-01-25 03:53

    Well, you'll definitely need to declare the variable in the scope you want it in. You can then set the value, and return it in one line:

    var Foo; // Declares Foo in this scope, though this expression has no L-Value
    return (Foo = 'bar'); // Sets Foo to 'bar' and returns the value of Foo
    

    It's questionable why you're doing this though. Ideally, Foo would be declared somewhere else in some parent scope. Or, you'd return a new function that would enclose the value of Foo.

提交回复
热议问题