Why doesn't this code:
<a href="#">Sample link</a>
<script>
setTimeout($('a').hide, 2000)
</script>
work like this one:
<a href="#">Sample link</a>
<script>
setTimeout(function(){ $('a').hide(); }, 2000)
</script>
Why doesn't this code:
<a href="#">Sample link</a>
<script>
setTimeout($('a').hide, 2000)
</script>
work like this one:
<a href="#">Sample link</a>
<script>
setTimeout(function(){ $('a').hide(); }, 2000)
</script>
The point is that this is bound to the global object inside setTimeout calls. It follows that both
setTimeout($('a').hide, 2000)
and
setTimeout(function(){ $('a').hide(); }, 2000)
will call the methos $('a').hide, but with different values for this (window in the first case and $('a') in the second).
Here are more details about the value of this according to the way you invoke a function.
The expression $('a').hide returns jQuery's standard hide function, without any reference to $('a').
When you call $('a').hide() as a statement, $('a') is passed as the this parameter to hide.
However, when you pass the hide function to setTimeout, it doesn't call the function on $('a'); all setTimeout'd functions are called on window.
And if you want that your line of code work, you should quote it:
setTimeout("$('a').hide()", 2000)
OR
Have a look to : http://www.w3schools.com/jsref/met_win_settimeout.asp