简体   繁体   English

有什么方法可以在 Javascript 中访问外部作用域中的局部作用域变量?

[英]Any way to access local scope variable in outer scope in Javascript?

Is there any way to make local scope variable accessible in outer scope without creating an object or without using 'this'?有什么方法可以在不创建对象或不使用“this”的情况下在外部范围内访问局部范围变量?

Say,说,

function foo(){
  var bar = 10;

}

Any way to make variable 'bar' available outside function 'foo' scope?有什么方法可以使变量“bar”在函数“foo”范围之外可用?

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: 将值分配给window对象的属性:

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? JavaScript中的变量范围是什么?

You can do something like this:你可以这样做:

var myScopedVariables = function foo(){
    var bar = 10;
    return [bar];
} 
console.log(myScopedVariables);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM