Sample link works like th...">

Question about javascript links

Why not this code:

<a href="#">Sample link</a> <script> setTimeout($('a').hide, 2000) </script> 

works like this:

 <a href="#">Sample link</a> <script> setTimeout(function(){ $('a').hide(); }, 2000) </script> 
+4
source share
4 answers

this because this bound to a global object inside setTimeout calls. It follows that both

 setTimeout($('a').hide, 2000) 

and

 setTimeout(function(){ $('a').hide(); }, 2000) 

will call the metos method $('a').hide , but with different values ​​for this ( window in the first case and $('a') in the second).

Here is more detailed information on the value of this according to how you call the function.

+3
source

The expression $('a').hide returns the standard jQuery hide function without reference to $('a') .
When you call $('a').hide() as an instruction, $('a') is passed as the this parameter to hide .

However, when you pass the hide function to setTimeout , it does not call the function on $('a') ; all setTimeout 'd functions are called on window .

+3
source

This problem. In JavaScript, this is the dotted notation used when calling the function that binds this - so when you pass the hide function in the first example, it is not associated with any particular jQuery object.

+2
source

And if you want your line of code to work, you should quote it:

 setTimeout("$('a').hide()", 2000) OR 

Take a look at: http://www.w3schools.com/jsref/met_win_settimeout.asp

-2
source

Source: https://habr.com/ru/post/1341148/


All Articles