简体   繁体   English

结束语和论点混乱

[英]Closure and argument confusion

I'm trying to understand why I'm getting different results when I'm working with callback functions and closures. 我试图理解为什么在使用回调函数和闭包时会得到不同的结果。

The first scenario: 第一种情况:

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

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

circle.animate(anim);

When running this, the circle in question animates, and after 2 seconds the a "anim done" message is displayed in the console. 运行此动画时,所讨论的圆会设置动画,并在2秒钟后在控制台中显示“动画完成”消息。

The second scenario: 第二种情况:

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

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

circle.animate(anim);

This causes the callback (cb) to be executed immediately. 这将导致回调(cb)立即执行。 This results in the "anim done" message to be displayed right away. 这导致立即显示“动画完成”消息。

Can someone clarify what is actually happening here? 有人可以澄清这里实际上发生了什么吗?

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: 如果要传递将调用该函数的函数,则必须使用function关键字将其包装在闭包中:

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

When you provide a callback, it must be a function. 提供回调时,它必须是一个函数。 cb("test") is not a function — it's the return value of a function. cb("test")不是函数-它是函数的返回值。 If you return something from cb("test") that is a function, it would work as expected. 如果从cb("test")返回某个函数,它将按预期工作。

As it is, you should do this: 实际上,您应该这样做:

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. 这样,您可以将函数而不是已经求值的表达式传递给动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM