Passing arguments in anonymous functions in JavaScript

后端 未结 5 1311
遥遥无期
遥遥无期 2021-02-02 11:29

Sometimes I see JavaScript that is written with an argument provided that already has a set value or is an object with methods. Take this jQuery example for instance:



        
5条回答
  •  情书的邮戳
    2021-02-02 11:48

    To me, this looks like were passing a function to the createServer function with two arguments that have methods already attached to them.

    No. They were passing a function to createServer that takes two arguments. Those functions will later be called with whatever argument the caller puts in. e.g.:

    function caller(otherFunction) {
         otherFunction(2);
     }
    caller(function(x) {
        console.log(x); 
    });
    

    Will print 2.

    More advanced, if this isn't what you want you can use the bind method belong to all functions, which will create a new function with specified arguments already bound. e.g.:

    caller(function(x) {
        console.log(x);
    }.bind(null, 3);
    });
    

    Will now print 3, and the argument 2 passed to the anonymous function will become an unused and unnamed argument.

    Anyway, that is a dense example; please check the linked documentation for bind to understand how binding works better.

提交回复
热议问题