0

我正在使用 Modernizr 运行触摸事件测试,测试似乎运行良好,但仍然是我仅在测试成功时才调用的函数。

这是测试:

Cluster.prototype.test_touch_event_support = function(callback) {
    return (Modernizr.touch) ? callback : log("Touch Support Undetected");
};

这是只有在测试成功时才应该运行的函数:

Cluster.prototype.initiate_shop_touch_events = function() {
    var self = this;
    return $("#" + this.shop_wrapper_id).hammer({prevent_default: true, drag_min_distance: Math.round(this.viewport_width * 0.1)}).bind("drag", function(ev) {
        var data = JSON.parse(self.get_local_storage_data(self.shop_data_key));
        var step = (ev.direction == "left") ? 1 : -1;
        var new_page = parseInt(data.current_page + step);
        return (new_page > 0 && new_page <= data.total_pages) ? $(self.shop_navigation_class).jPages(new_page) : false;
});
};

而且我正在检查,即使它不依赖于我传递给测试的论点:

self.test_touch_event_support(self.initiate_shop_touch_events());

有人可以告诉我为什么该功能仍在运行吗?因为我还在控制台中收到不支持触摸事件的消息。

4

1 回答 1

2
self.test_touch_event_support(self.initiate_shop_touch_events());

调用self.initiate_shop_touch_events 的结果传递给 self.test_touch_event_support

你需要做:

self.test_touch_event_support(self.initiate_shop_touch_events);

传递函数。

Cluster.prototype.test_touch_event_support = function(callback) {
    return (Modernizr.touch) ? callback : log("Touch Support Undetected");
};

您需要调用回调而不是引用它。

Cluster.prototype.test_touch_event_support = function(callback) {
    return (Modernizr.touch) ? callback.call (this) : log("Touch Support Undetected");
};

教训:

  1. 了解调用函数和引用函数之间的区别。与许多编程语言不同,JavaScript 中的函数是一流的实体。您可以通过调用它们的名称来传递对它们的引用。要调用、调用或执行一个函数,您必须在函数引用之后立即指定一个用括号括起来的参数列表(可能为空)。
  2. 调用时,所有函数都会传递一个上下文参数,该参数使用this函数体中的单词引用。这通常通过在函数名称前加上对象引用来指定,例如obj.func (123)在此调用中,obj每次函数体引用时都将使用该对象this。使用这种用法,函数必须是对象的已定义方法。函数的callandapply方法可以用来显式指定这个上下文参数:func.call (obj, 123)相当于上面的 when funcis not a method obj

更多细节可以在这里找到https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

于 2012-05-27T09:55:12.023 回答