以下哪种形式将lambda传递给jQuery的document.ready事件是正确的?

时间:2015-08-19 23:52:11

标签: javascript jquery

我有一个名为var foo = new function() { var OnDocumentReady = function() { ... } } 的对象,我在其中使用事件处理程序封装了jQuery的document.ready事件。

$(document).ready(foo.OnDocumentReady);

$(document).ready(foo().OnDocumentReady);

$(document).ready(foo()["OnDocumentReady"]);

但是,在尝试任何这些表单时,我的事件处理程序不会被调用。

    while (int returnValue = pcap_next_ex(pcap, &header, &data) >= 0)
{
    // Print using printf. See printf reference:
    // http://www.cplusplus.com/reference/clibrary/cstdio/printf/

    // Show the packet number
    printf("Packet # %i\n", ++packetCount);

    // Show the size in bytes of the packet
    printf("Packet size: %d bytes\n", header->len);

    // Show a warning if the length captured is different
    if (header->len != header->caplen)
        printf("Warning! Capture size different than packet size: %ld bytes\n", header->len);

    // Show Epoch Time
    printf("Epoch Time: %d:%d seconds\n", header->ts.tv_sec, header->ts.tv_usec);

    // loop through the packet and print it as hexidecimal representations of octets
    // We also have a function that does this similarly below: PrintData()
    for (u_int i=0; (i < header->caplen ) ; i++)
    {
        // Start printing on the next after every 16 octets
        if ( (i % 16) == 0) printf("\n");

        // Print each octet as hex (x), make sure there is always two characters (.2).
        printf("%.2x ", data[i]);
    }

    // Add two lines between packets
    printf("\n\n");
}

1 个答案:

答案 0 :(得分:3)

这是因为您已将OnDocumentReady本地作用于foo内的变量环境。您需要将其实际附加为foo的属性。您可以使用this

执行此操作
var foo = new function()
{
  this.OnDocumentReady = function() { ... }
}

现在你的第一种方法将起作用:

$(document).ready(foo.OnDocumentReady);

其他两个将无法工作,因为使用new function()将构造一个对象,这不是一个函数。将对象作为函数调用将导致异常。

相关问题