我想知道是否可以在node.js脚本中为变量分配方法,然后能够通过a调用该方法。符号(类似于需要的东西,除了我不是从磁盘读取此文件或方法)而是可以动态分配。
这里的想法是能够动态地改变该方法允许脚本引用相同变量和调用的内容,但在更新方法时获得不同的结果。
答案 0 :(得分:1)
我非常确定这听起来好像是在尝试更改在运行时分配为对象属性的函数并调用。如果这就是您的要求,那么是。你可以做到这一点。请考虑以下代码和注释。
函数只是可以像任何其他对象一样传递的对象。你可以将它们分配给变量,将它们作为参数传递,然后用它们做任何你想做的事情。
/*jslint node:true devel:true*/
"use strict";
/*
* Here we define 2 functions that
* will simply print to console
*/
function func1() {
console.log("Hello World");
}
function func2() {
console.log("Foo bar");
}
// Next we declare an object and a counter
var myObject = {},
counter = 0;
/*
* Now we are giving our object a property, "funcToUse"
* and assigning one of the functions we defined earlier
* to that property.
*/
myObject.funcToUse = func1;
/*
* Now we are defining a function that we will have run
* in a timeout and do so as long as counter is less than 5
*/
function timeoutFunc() {
/*
* Here we call the function that we assigned
* to the property "funcToUse" just as we would
* normally call any other function with "()"
*/
myObject.funcToUse();
/*
* Now were going to change which function is
* assigned to the object property. If it was func1
* it becomes func2 and vice versa.
*/
if (myObject.funcToUse === func1) {
myObject.funcToUse = func2;
} else {
myObject.funcToUse = func1;
}
// This just restarts the timeout
if (counter < 5) {
counter += 1;
setTimeout(timeoutFunc, 2000);
}
}
// This bootstraps the timeout
setTimeout(timeoutFunc, 2000);
<强>输出:强>
Hello World
Foo bar
Hello World
Foo bar
Hello World
Foo bar