Calling a function in JavaScript without parentheses

前端 未结 7 1665
醉梦人生
醉梦人生 2020-12-09 07:27

Is there a way in JavaScript to call a function without parentheses?

For example in jQuery:

$(\'#wrap\').text(\"asdf\"); will work and so will <

7条回答
  •  余生分开走
    2020-12-09 07:51

    new


    You can call a function using new. The twist is, within the function this becomes an object being constructed by the function instead of whatever it would normally be.

    function test () { alert('it worked'); }
    ...
    new test; // alerts "it worked"
    

    call and apply


    You can use call or apply to call a function indirectly. You'll still need parentheses (unless you use new), but you won't be directly invoking the function with parentheses.

提交回复
热议问题