par*_*ars 50 javascript node.js
在客户端,您可以通过window["functionName"](arguments)
.如何在node.js服务器端代码中实现?
rav*_*avi 119
如果在模块中需要这样的功能,那么一个hack就是将这些模块函数存储在模块中的变量中,然后通过从模块对象属性访问它们来调用它们.例:
var x = { }; // better would be to have module create an object
x.f1 = function()
{
console.log('Call me as a string!');
}
Run Code Online (Sandbox Code Playgroud)
现在,在模块中,您可以使用字符串中的值来调用它:
var funcstr = "f1";
x[funcstr]();
Run Code Online (Sandbox Code Playgroud)
我正在学习Node自己的绳索,上面可能有各种各样的错误:-).也许编写这个例子的方法稍微好一些(对于模块m.js):
module.exports =
{
f1: function() { console.log("Call me from a string!"); },
f2: function(str1) { this[str1](); }
}
Run Code Online (Sandbox Code Playgroud)
现在你可以:
var m = require('m.js');
m.f2('f1');
Run Code Online (Sandbox Code Playgroud)
甚至只是:
var m = require('m.js');
m['f1']();
Run Code Online (Sandbox Code Playgroud)
FWIW!
Mar*_*ahn 12
您正在寻找 global
但请注意,在模块中没有任何东西暴露在这个级别
Jer*_*yal 10
将所有方法定义为Handler的属性:
var Handler={};
Handler.application_run = function (name) {
console.log(name)
}
Run Code Online (Sandbox Code Playgroud)
现在这样称呼它
var somefunc = "application_run";
Handler[somefunc]('jerry codes');
Run Code Online (Sandbox Code Playgroud)
输出:杰里代码
// Handler.js
module.exports={
application_run: function (name) {
console.log(name)
}
}
Run Code Online (Sandbox Code Playgroud)
使用方法在Handler.js
中定义different.js
:
// different.js
var methods = require('./Handler.js') // path to Handler.js
methods['application_run']('jerry codes')
Run Code Online (Sandbox Code Playgroud)
输出:杰里代码
小智 5
如果您在模块范围内需要它,您可以使用类似的东西
var module = require('moduleName');
module['functionName'](arguments);
Run Code Online (Sandbox Code Playgroud)
小智 5
老实说,看看所有这些答案,它们似乎有点太多了。我正在尝试寻找其他方法来解决这个问题。您可以使用该eval()
命令将变量打印为文本,然后将其作为函数调用
IE
let commands = ['add', 'remove', 'test'];
for (i in commands) {
if (commands[i] == command) {
var c = "proxy_"+command;
eval(c)(proxy);
}
}
Run Code Online (Sandbox Code Playgroud)
eval(string)(arg1, arg2);
此示例脚本将执行该函数proxy_test(proxy)
If you want to call a class level function using this
then following is the solution and it worked for me
class Hello {
sayHello(name) {
console.log("Hello " + name)
}
callVariableMethod() {
let method_name = 'sayHello'
this[`${method_name}`]("Zeal Nagar!")
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
50192 次 |
最近记录: |