如何获取函数内创建的变量? [英] How to get the variables that were created inside a function?
本文介绍了如何获取函数内创建的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在node.js中执行javascript文件,我需要访问在该文件中创建的所有变量。由于这些javascript文件可以包含任何内容,具体取决于开发人员上下文,我需要以编程方式访问变量。
I'm executing javascript files in node.js, and I need to access all the variables that were created in that file. Since these javascript files can hold anything depending on the developer context I need to access the variables programatically.
我的问题是:如何获取在函数内创建的变量?这样的事情:
My question is: How to get the variables that were created inside a function? Something like this:
function test(){
var a = 'hello world';
var b = 100;
}
console.log(test.variables);
// -> { "a": 'hello world', "b": 100 }
这有可能吗?
推荐答案
不,您需要在对象中返回这些值。
No, you need to return those values in an object.
function test(){
var a = 'hello world',
b = 100;
return {
a: a,
b: b
};
}
console.log(test); // { "a": 'hello world', "b": 100 }
或者你可以将这些值保存到函数范围之外的变量:
Or you can save those values to a variable that exists outside of the function scope:
var variables = null;
function test(){
var a = 'hello world',
b = 100;
variables = {
a: a,
b: b
};
}
console.log(variables); // { "a": 'hello world', "b": 100 }
这篇关于如何获取函数内创建的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文