简体   繁体   中英

javascript callback function in chrome extension

I am trying to understand chrome extension code, which is written by javascript. But there is one code related to callback function I don't understand.

function dumpBookmarks(query) {
  var bookmarkTreeNodes = chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
  $('#bookmarks').append(dumpTreeNodes(bookmarkTreeNodes, query));
});
} 

For my understanding, I find that call back function should run latter, which means bookmarkTreeNodes in the inside function should come from var bookmakrTreeNodes (come from chrome.bookmakrs.getTree function). But, when I change var bookmarkTreeNodes to anything else and keep bookmarkTreeNodes in the inside function the same, the program run well. This result conflicts with my idea.

Where is bookmakrTreeNodes in inside function coming from? How can it come before chrome.bookmarks.getTree() function?

Thanks!

Your understanding of callbacks is incorrect. The function you pass to getTree takes an argument bookmarkTreeNodes which has nothing to do with the var bookmarkTreeNodes you declared outside the function.

Imagine it this way: the function chrome.bookmarks.getTree is written something like this.

chrome.bookmarks.getTree = function (cb) {
    var bookmarkTreeNodes;
    /* do some work to get the tree nodes */
    cb(bookmarkTreeNodes);
    // maybe return something here. 
    //This is the value your "var bookmarkTreeNodes" would take on eventually
    //but as you can see, it has nothing to do with what is passed to your callback.
}

Now do you see where the callback's argument is coming from? I suggest you read some more about dealing with callbacks because it's a very important part of JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM