我在 node.js 中执行 javascript 文件,我需要访问在该文件中创建的所有变量。由于这些 javascript 文件可以根据开发人员上下文保存任何内容,因此我需要以编程方式访问变量。
我的问题是:如何获取函数内部创建的变量?像这样:
function test(){
var a = 'hello world';
var b = 100;
}
console.log(test.variables);
// -> { "a": 'hello world', "b": 100 }
这有可能吗?
最佳答案
不,您需要在对象中返回这些值。
function test(){
var a = 'hello world',
b = 100;
return {
a: a,
b: b
};
}
console.log(test); // { "a": 'hello world', "b": 100 }
或者您可以将这些值保存到函数范围之外的变量中:
var variables = null;
function test(){
var a = 'hello world',
b = 100;
variables = {
a: a,
b: b
};
}
console.log(variables); // { "a": 'hello world', "b": 100 }
关于javascript - 如何获取函数内部创建的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15753308/