带或不带括号传递事件处理程序()

时间:2017-04-18 00:12:07

标签: javascript

我的问题是为什么myFunction2立即被触发,javascript如何工作?感谢。

<!--when passing "myFunction1" without (), myFunction1 is triggered after 3 seconds as expected-->
<button onclick="setTimeout(myFunction1, 3000);">Try it 1</button>

<script>
function myFunction1() {
    alert('Hello');
}
</script>

<!--when passing "myFunction2" with (), myFunction1 is triggered right away as clicking the button-->
<button onclick="setTimeout(myFunction2(), 3000);">Try it 2</button>

<script>
function myFunction2() {
    alert('Hello');
} 
</script>

0 个答案:

没有答案