从事件侦听器调用自执行函数

Calling a Self-Executing Function from an Event Listener

假设这是我唯一的 HTML

<input id="target" type="number">

假设这是我唯一的 JavaScript

var target = document.getElementById('target');

我想在输入更改时执行 function,但我也想在页面加载时执行一次 functionSelf-Executing FunctionIIFE ).以下是 3 个示例,其中 1 个不起作用。



以下按预期工作:

target.addEventListener('input', myFunction);

function myFunction(){
    console.log('executed!');
}
myFunction();

此处function将在页面加载时执行。它不会由 eventListener 执行,而是将 ReferenceError: myFunction is not defined 记录到控制台:

target.addEventListener('input', function(){
    myFunction();
});

(function myFunction(){
    console.log('executed!');
})();

这个既不会在页面加载时执行,也不会被 eventListener 执行,并将 ReferenceError: myFunction is not defined 记录到控制台:

target.addEventListener('input', myFunction);

(function myFunction(){
    console.log('executed!');
})();


我的问题:为什么第三个例子不起作用?

IIFE 的全部意义在于防止全局(或更高)范围的污染。它不起作用,因为立即调用函数表达式 (IIFE) 是匿名函数。因此,当您使用名称设置 IIFE 语法时,表达式之外的函数名称将被忽略。

来自MDN:

IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

It is a design pattern which is also known as Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.

The second part is creating the immediately executing function expression (), through which the JavaScript engine will directly interpret the function.

此外,出于同样的原因,您的第二个示例实际上不起作用。您确实看到了 executed! 消息,但那是因为 IIFE 会自动执行。如果您继续更改输入的值,您将收到与选项 #3 相同的错误。

var target = document.getElementById('target');

target.addEventListener('input', function(){
    myFunction();
});

(function myFunction(){
    console.log('executed!');
})();
<input id="target" type="number">