为什么JavaScript将源代码文本传递给参数?

时间:2014-02-23 02:52:44

标签: javascript

http://jsfiddle.net/JonnyD/H2Dpe/3/

控制台日志:

   [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
     (index):104

   function (newFeedItems) {
       console.log(feedItems);
   } (index):113

   Uncaught TypeError: Object function (newFeedItems) {
      console.log(feedItems);
   } has no method 'sort' 

从哪里得到这个?

function (newFeedItems) {
    console.log(feedItems);
} (index):113

当它应该是:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

查看函数fetchFeeds()processLatestFeed()。问题始于processLatestFeed(function(newFeedItems) {

function fetchFeeds() {
    fetchVideos(function(newVideoItems) {
        fetchPodcasts(function(newPodcastItems) {
            var newFeedItems = newVideoItems.concat(newPodcastItems);
            console.log(newFeedItems);
            processLatestFeed(function(newFeedItems) {
                console.log(feedItems);
            });
        });
    });
}

function processLatestFeed(newFeedItems, callback) {
    console.log(newFeedItems);
    newFeedItems.sort(function(a,b) {return (a.date > b.date) ? -1 : ((b.date > a.date) ? 1 : 0);});

    for (i in newFeedItems) {
        var newItem = newFeedItems[i];

        if (!isItemInFeed(newItem)) {
            feedItems.push(newItem);
        }

        if (feedItems.length == 50) {
            break;   
        }
    }

    callback();
}

1 个答案:

答案 0 :(得分:1)

您正在将函数作为第一个参数传递给processLatestFeed

processLatestFeed(function(newFeedItems) {
  console.log(feedItems);
});

但您定义了该函数以接受数组作为第一个参数,将回调定义为 second 参数:

function processLatestFeed(newFeedItems, callback) {
    console.log(newFeedItems); // <- this logs the function source
    // ...
}

所以你必须把这个函数称为

processLatestFeed(newFeedItems, function() {
  // you are not passing an arguments to the callback
});