1

处理一些javascript。我发现了一个很好的函数来计算光标的速度。问题是我想返回实际值,而不是回调。你会怎么做?

        function makeVelocityCalculator(e_init, callback) {
        var x = e_init.clientX,
            y = e_init.clientY,
            t = Date.now();
        return function(e) {
            var new_x = e.clientX,
                new_y = e.clientY,
                new_t = Date.now();
            var x_dist = new_x - x,
                y_dist = new_y - y,
                interval = new_t - t;
            // update values:
            x = new_x;
            y = new_y;
            t = new_t;
            var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
            callback(velocity);
        };
    }
4

2 回答 2

2

好吧,然后将该函数更改为返回速度,而不是“回调(速度)”

Js Fiddle 示例

或者您可以按照预期的方式使用它

makeVelocityCalculator(initialEvent, function(velocity) {
   console.log("velocity is", velocity);
});
is pretty much same as 
var velocity = makeVelocityCalculator(initialEvent);
console.log("velocity is", velocity);
于 2013-11-05T16:49:59.630 回答
1
 function calculateVelocity(e_init) {
    var x = e_init.clientX,
        y = e_init.clientY,
        t = Date.now();
    return function(e) {
        var new_x = e.clientX,
            new_y = e.clientY,
            new_t = Date.now();
        var x_dist = new_x - x,
            y_dist = new_y - y,
            interval = new_t - t;
        // update values:
        x = new_x;
        y = new_y;
        t = new_t;
        var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
        return velocity;
    };
}

var velocity = calculateVelocity(e_init)(e);
// OR
var v_f = calculateVelocity(e_init);
// then some code ...
v_f(e);

(function(){})()如果您希望调用calculateVelocity返回速度,请使用立即调用函数,否则返回该函数,该函数又返回速度。

于 2013-11-05T16:49:50.233 回答