What's the meaning of “()” in a function call?

前端 未结 4 2027
清酒与你
清酒与你 2020-12-29 05:53

Now, I usually call a function (that requires no arguments) with () like this:

myFunction(); //there\'s empty parens

Except in

4条回答
  •  太阳男子
    2020-12-29 06:50

    Your jQuery bind example is similar to setTimeout(monitor, 100);, you are passing a reference of a function object as an argument.

    Passing a string to the setTimeout/setInterval methods should be avoided for the same reasons you should avoid eval and the Function constructor when it is unnecessary.

    The code passed as a string will be evaluated and run in the global execution context, which can give you "scope issues", consider the following example:

    // a global function
    var f = function () {
      alert('global');
    };
    
    (function () {
      // a local function
      var f = function() {
        alert('local');
      };
    
      setTimeout('f()', 100); // will alert "global"
      setTimeout(f, 100);     // will alert "local"
    })();
    

    The first setTimeout call in the above example, will execute the global f function, because the evaluated code has no access to the local lexical scope of the anonymous function.

    If you pass the reference of a function object to the setTimeout method -like in the second setTimeout call- the exact same function you refer in the current scope will be executed.

提交回复
热议问题