Let's say I have this code:
假设我有这个代码:
Person = {};
var person = new Person();
Where Person is a class I defined in the file Person.js. Before invoking the code that executes above, I want to check to see if the Person class exists and if not I want to include it using require('./'+className). Doing this all dynamically, I only have a string to start with:
Person是我在Person.js文件中定义的类。在调用上面执行的代码之前,我想检查Person类是否存在,如果不是,我想使用require('./'+ className)来包含它。动态地完成这一切,我只有一个字符串开头:
var className = 'Person';
How do I use my className string to identify if Person exists in Node JS? I know in the browser I can do this:
如何使用我的className字符串来识别Node JS中是否存在Person?我知道在浏览器中我可以这样做:
if(window[className])
2 个解决方案
#1
1
Ah, I figured it out. In Node you can do:
啊,我明白了。在Node中,您可以:
var className = 'Person';
if(global[className])
#2
0
It's impossible with Node.js to access the variables declared with var
, and, as it is impossible to get a variable from a string in Javascript, you can not do what you want.
Node.js无法访问用var声明的变量,并且由于无法从Javascript中的字符串中获取变量,因此无法执行您想要的操作。
However, there should be another way to do what you want, if it is really a necessity, maybe you can use some dirty tricks like the one described here (it may not work given your project architecture):
但是,应该有另一种方法来做你想要的,如果它确实是必需的,也许你可以使用像这里描述的一些肮脏的技巧(它可能不适用于你的项目架构):
Get all defined variables in scope in node.js
获取node.js中范围内的所有已定义变量
#1
1
Ah, I figured it out. In Node you can do:
啊,我明白了。在Node中,您可以:
var className = 'Person';
if(global[className])
#2
0
It's impossible with Node.js to access the variables declared with var
, and, as it is impossible to get a variable from a string in Javascript, you can not do what you want.
Node.js无法访问用var声明的变量,并且由于无法从Javascript中的字符串中获取变量,因此无法执行您想要的操作。
However, there should be another way to do what you want, if it is really a necessity, maybe you can use some dirty tricks like the one described here (it may not work given your project architecture):
但是,应该有另一种方法来做你想要的,如果它确实是必需的,也许你可以使用像这里描述的一些肮脏的技巧(它可能不适用于你的项目架构):
Get all defined variables in scope in node.js
获取node.js中范围内的所有已定义变量