0

我试图理解为什么在使用回调函数和闭包时会得到不同的结果。

第一个场景:

var cb = function(){
   console.log("anim done");
} 

var anim = Raphael.animation({
    transform: 't0, 100'
}, 2000, cb);

circle.animate(anim);

运行此程序时,有问题的圆圈会动画,2 秒后控制台中会显示“动画完成”消息。

第二种情况:

var cb = function(msg){
   console.log("anim done");
} 

var anim = Raphael.animation({
    transform: 't0, 100'
}, 2000, cb("test"));

circle.animate(anim);

这会导致回调 (cb) 立即执行。这会导致立即显示“动画完成”消息。

有人可以澄清这里实际发生的事情吗?

4

2 回答 2

1

When you put a function name all by itself, it just evaluates to the function (a function name is essentially just a variable whose value is the function.

When you follow a function name with parentheses, it means to call the function at that time, with the given arguments. The value is what the function returns.

If you want to pass a function that will call the function, you have to wrap it in a closure, using the function keyword:

var anim = Raphael.animation({
    transform: 't0, 100'
}, 2000, function() {cb("test")});
于 2013-02-09T01:28:01.677 回答
0

当您提供回调时,它必须是一个函数。cb("test")不是函数——它是函数的返回值。如果你从cb("test")那个函数返回一些东西,它会按预期工作。

事实上,你应该这样做:

var anim = Raphael.animation({
    transform: 't0, 100'
}, 2000, function() {
    cb("test");
});

This way you pass a function, and not an already-evaluated expression, to the animation.

于 2013-02-09T01:27:54.377 回答