Javascript变量作为闭包的范围在回调中

时间:2014-08-25 15:14:17

标签: javascript variables scope anonymous-function

我有这个:

$(document).ready(function(){

pubnub.subscribe ({
    connect: function(m){

        var channelLatestMessages = [];

        pubnub.history({
          channel: broadcastChannel,
          count: 1,
          callback: function (m) {
            if(m[0].length > 0)
            {
                $.each(m[0], function(index, value){
                    channelLatestMessages.push(value);
                });
            }
            //THE NUMBER OF MESSAGE OBJECTS RETURNED IS 2
            //HERE THE OUTPUT IS 2
            console.info(channelLatestMessages.length);
          },
        }); 

        //THE NUMBER OF MESSAGE OBJECTS RETURNED IS 2
        //HERE THE OUTPUT IS 0          
        console.info(channelLatestMessages);
    }
});

});

如果我宣布:

channelLatestMessages = [];

在Firebug控制台中没有var关键字和页面加载问题之后

console.info(channelLatestMessages.length);

号码为2

但我再次在代码中获得channelLatestMessages.length 0的值。

这怎么可能?

1 个答案:

答案 0 :(得分:1)

因为在一种情况下,你在之后测试长度导致回调运行的事件被触发,而在另一种情况下你在那之前测试它。