javascript语法:函数调用和使用括号

mad*_*lor 7 javascript syntax

为什么这个工作..

<script type="text/javascript">
<!-- 

function myAlert(){
    alert('magic!!!');
}


if(document.addEventListener){   
    myForm.addEventListener('submit',myAlert,false); 
}else{   
    myForm.attachEvent('onsubmit',myAlert); 
}
// -->
</script>
Run Code Online (Sandbox Code Playgroud)

但不是这个????

<script type="text/javascript">
<!-- 

function myAlert(){
    alert('magic!!!');
}


if(document.addEventListener){   
    myForm.addEventListener('submit',myAlert(),false); 
}else{   
    myForm.attachEvent('onsubmit',myAlert()); 
}
// -->
</script>
Run Code Online (Sandbox Code Playgroud)

不同之处在于调用myAlert函数时使用括号.

我得到的错误..

"htmlfile:类型不匹配." 通过VS2008进行编译时.

Luc*_*eis 30

函数后面的()表示执行函数本身并返回它的值.如果没有它,您只需拥有该函数,该函数可作为回调传递.

var f1 = function() { return 1; }; // 'f1' holds the function itself, not the value '1'
var f2 = function() { return 1; }(); // 'f2' holds the value '1' because we're executing it with the parenthesis after the function definition

var a = f1(); // we are now executing the function 'f1' which return value will be assigned to 'a'
var b = f2(); // we are executing 'f2' which is the value 1. We can only execute functions so this won't work
Run Code Online (Sandbox Code Playgroud)


coo*_*ird 5

所述的addEventListener函数期望的功能或实现一个对象EventListener作为第二个参数,而不是函数调用.

当将()它们添加到函数名称时,它是函数调用而不是函数本身.

编辑:如其他响应和注释中所示,可以在Javascript中返回函数.

所以,对于有趣的事情,我们可以尝试以下方法.从原始版本开始myAlert,我们可以稍微更改它以返回不同的消息,具体取决于参数:

function myAlert(msg)
{
    return function()
    {
        alert("Message: " + msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,请注意该函数实际返回一个函数.因此,为了调用该函数,()将需要额外的功能.

我写了一些HTML和Javascript来使用上面的功能.(请原谅我不干净的HTML和Javascript,因为它不是我的域名):

<script type="text/javascript">

function myAlert(msg)
{
    return function()
    {
        alert("Message: " + msg);
    }
}

</script>

<html>
<body>

<form>
<input type="button" value="Button1" onclick="myAlert('Clicked Button1')()">
<input type="button" value="Button2" onclick="myAlert('Clicked Button2')()">
</form>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

显示两个按钮,每个按钮将myAlert使用不同的参数调用该功能.一旦myAlert函数被调用,它本身会返回另一个function这样就必须有一组额外的括号来调用.

最终结果是,点击Button1将显示带消息的消息框Message: Clicked Button1,而点击Button2则会显示一个消息框说明Message: Clicked Button2.