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
5 Answers
Reset to default 7No. 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
版权声明:本文标题:Any way to access local scope variable in outer scope in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741418113a2377639.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论