本文介绍了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
函数时使用括号.
the difference being the use of parenthesis when calling the myAlert
function.
我得到的错误..
"htmlfile: 类型不匹配."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 语法:函数调用和使用括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!