admin管理员组

文章数量:1289586

Is there any way to make local scope variable accessible in outer scope without creating an object or without using 'this'?

Say,

function foo(){
  var bar = 10;

}

Any way to make variable 'bar' available outside function 'foo' scope?

Is there any way to make local scope variable accessible in outer scope without creating an object or without using 'this'?

Say,

function foo(){
  var bar = 10;

}

Any way to make variable 'bar' available outside function 'foo' scope?

Share Improve this question asked Sep 13, 2015 at 12:41 nim007nim007 3,0583 gold badges20 silver badges30 bronze badges 4
  • If you don't want that variable local to that function, define it outside the function... – Andy Commented Sep 13, 2015 at 12:44
  • 1 It doesn't make much sense to me. Local scope is designed to be local why would you want it to be part of any other scope? – MinusFour Commented Sep 13, 2015 at 12:46
  • It was an interview question, any way to make it available in the outer scope on some condition. – nim007 Commented Sep 13, 2015 at 12:49
  • 1 You can make it available to the outer scope but then it wouldn't be local anymore. – MinusFour Commented Sep 13, 2015 at 12:50
Add a ment  | 

5 Answers 5

Reset to default 7

No. Simply you can't. Scope is scope. If you want to access outside, make it declare outside and use it.

That's how things designed. I don't suggest any crappy way to make it possible.

Assign the value to a property of the window object:

function foo(){
    window.bar = 10;
}

console.log(window.bar); //10

EDIT:

Since you can't accept his answer, then no - what you're asking for is impossible. Only solution is to declare the variable in the global scope, then initialize it later.

You can't access local variable outside the function.

Following post might help you to understand scopes in more detail -

What is the scope of variables in JavaScript?

You can do something like this:

var myScopedVariables = function foo(){
    var bar = 10;
    return [bar];
} 
console.log(myScopedVariables);
function myFunction() { myVar = 'Hello'; // global variable } myFunction(); console.log(myVar); // output: "Hello"

本文标签: Any way to access local scope variable in outer scope in JavascriptStack Overflow