Reputation: 3058
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?
Upvotes: 3
Views: 2818
Reputation: 1
function myFunction() { myVar = 'Hello'; // global variable } myFunction(); console.log(myVar); // output: "Hello"
Upvotes: 0
Reputation: 115
You can do something like this:
var myScopedVariables = function foo(){
var bar = 10;
return [bar];
}
console.log(myScopedVariables);
Upvotes: 1
Reputation: 2349
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?
Upvotes: 2
Reputation: 3098
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.
Upvotes: 2
Reputation: 122026
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.
Upvotes: 7