为什么在触发事件之前调用事件句柄中的立即调用函数?

let a = (function gigel() {

    alert("dd");

})(); 

* this is executed immediatly as the page loads*

    <button onclick="a">Click me</button>


* this is executed only when clicking the button *

    <button onclick="alert('dd')">Click me</button> 


动漫人物
浏览 113回答 1
1回答

偶然的你

您正在调用事件(function gigel...)(),因为调用返回任何内容a都不是函数。也a没有被调用,你会想要以下内容:let a = (function gigel() {&nbsp; alert("IIFE");});* this is executed immediately as the page loads*<button onclick="a()">Click me</button>&nbsp;* this is executed only when clicking the button *<button onclick="alert('dd')">Click me</button>或者,如果您想立即调用它并将其存储在a:let a = (function gigel() {&nbsp; alert("IIFE");&nbsp; return gigel;})();* this is executed immediately as the page loads*<button onclick="a()">Click me</button>&nbsp;* this is executed only when clicking the button *<button onclick="alert('dd')">Click me</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript