Javascript anonymous function vs normal function
What's the difference between:
<script type="text/javascript">
$().ready(function() {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=SomeLink]").click(function() {
if (!CompareDictionaries(InitialDictionary))
{
alert('Hello')
开发者_Python百科 }
}
)
})
</script>
and
<script type="text/javascript">
$().ready(function () {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=SomeLink]").click(CheckValuesChanged(InitialDictionary));
})
function CheckValuesChanged(InitialDictionary) {
if (!CompareDictionaries(InitialDictionary))
{
alert('Hello')
}
}
</script>
Without going into details into what I'm trying to achieve here, is there any reason why an anonymous method works fine and the call to a function doesn't? Shouldn't they produce the same results?
To call a function you have to do this:
$("a[id*=LogoLink]").click(function(){CheckValuesChanged(InitialDictionary)});
Or:
$("a[id*=LogoLink]").click("CheckValuesChanged(InitialDictionary)"); //might work
They both work, but you cannot bind a function to an event like this
$("a[id*=LogoLink]").click(CheckValuesChanged(InitialDictionary));
because the a function must be bound to the click event. When you pass an argument to the function it returns undefined
, which is not a function. You can fix this by changing your second code sample like so:
$().ready(function () {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=LogoLink]").click(CheckValuesChanged);
function CheckValuesChanged() {
if (!CompareDictionaries(InitialDictionary)) {
alert('Hello')
}
}
});
The second example is wrong:
$("a[id*=LogoLink]").click(CheckValuesChanged(InitialDictionary));
It should be:
$("a[id*=LogoLink]").click(CheckValuesChanged);
But because you want to pass InitialDictionary
as argument you need to use the first approach which will capture it in the anonymous function.
精彩评论