我可以在变量中创建一个递归函数,如下所示:
/* Count down to 0 recursively.
*/
var functionHolder = function (counter) {
output(counter);
if (counter > 0) {
functionHolder(counter-1);
}
}
Run Code Online (Sandbox Code Playgroud)
有了这个,functionHolder(3);就输出了3 2 1 0.假设我做了以下事情:
var copyFunction = functionHolder;
Run Code Online (Sandbox Code Playgroud)
copyFunction(3);输出3 2 1 0如上.如果我改变functionHolder如下:
functionHolder = function(whatever) {
output("Stop counting!");
Run Code Online (Sandbox Code Playgroud)
然后functionHolder(3);会Stop counting!按预期给出.
copyFunction(3);现在给3 Stop counting!它指的是functionHolder,不是函数(它本身指向).在某些情况下这可能是理想的,但是有没有办法编写函数以便它调用自身而不是保存它的变量?
也就是说,是否可以仅更改线路,functionHolder(counter-1);以便3 2 1 0在我们呼叫时仍然通过所有这些步骤copyFunction(3);?我尝试了,this(counter-1);但这给了我错误this is …
好吧,所以我一直在看函数并将它们用作参数.假设我有一个函数,它接受一个函数并执行它:
function run(someFunction,someArgument) {
someFunction(someArgument);
}
Run Code Online (Sandbox Code Playgroud)
我看到我可以通过一个现有的功能,说:
function foo(bar) {
// foo that bar!
}
Run Code Online (Sandbox Code Playgroud)
通过调用run(foo,bar);我也可以在动态对象中组成一个函数并运行它:
var whiteBoy = {
playThat: function(funkyMusic) {
// funk out in every way
}
};
Run Code Online (Sandbox Code Playgroud)
然后我调用run(whiteBoy.playThat,funkyMusic);我想要做的是在调用中定义一个函数,如下所示:
run(/* define a new function */,relevantArgument);
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?