javascript语法:函数调用和使用括号 [英] javascript syntax: function calls and using parenthesis
本文介绍了javascript语法:函数调用和使用括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这样做..
<script type="text/javascript">
<!--
function myAlert(){
alert('magic!!!');
}
if(document.addEventListener){
myForm.addEventListener('submit',myAlert,false);
}else{
myForm.attachEvent('onsubmit',myAlert);
}
// -->
</script>
但不是这个????
<script type="text/javascript">
<!--
function myAlert(){
alert('magic!!!');
}
if(document.addEventListener){
myForm.addEventListener('submit',myAlert(),false);
}else{
myForm.attachEvent('onsubmit',myAlert());
}
// -->
</script>
区别在于调用 myAlert $ c时使用括号$ c> function。
the difference being the use of parenthesis when calling the myAlert
function.
我得到的错误..
htmlfile : 类型不匹配。通过VS2008编译时。
"htmlfile: Type mismatch." when compiling via VS2008.
推荐答案
()之后函数意味着执行函数本身并返回它的值。如果没有它,你只需要有一个函数,它可以作为回调传递。
The () after a function means to execute the function itself and return it's value. Without it you simply have the function, which can be useful to pass around as a callback.
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
这篇关于javascript语法:函数调用和使用括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文