How does the load() function allow the user to provide a callback?

前端 未结 6 791
再見小時候
再見小時候 2020-12-30 13:27

In javascript it\'s very popular for libraries/frameworks to let us define a callback function for post-processing of data.

eg.

load(\"5\", function(         


        
6条回答
  •  梦毁少年i
    2020-12-30 13:30

    Well, the load function could look like this:

    function load(arg, callback) {
    
      var element = { name: "foo " + arg }; // something to pass
    
      if (typeof callback == 'function') {
        callback(element);
      }
    }
    

    With the typeof check we make sure that the callback argument is an object that we can invoke, a function.

    Then your example:

    load("5", function(element) {
        alert(element.name); // Will show `"foo 5"`.
    });
    

提交回复
热议问题