`setTimeout` passed through the string returns an error

These are two parts of identical code; but the first one works correctly:

function dismiss(obj) {setTimeout(function() {obj.style.display = "none";}, 20);}

and the second returns error: obj is not defined:

function dismiss(obj) {setTimeout('obj.style.display = "none"', 20);}

Why is this so?
PS: Example

+4
source share
4 answers

The answer lies in closures , or in more detail .

In the first example, the variable objis fixed when an anonymous function is created. When the function starts, the captured link is objused to access stylewhich works fine.

, eval setTimeout, Mozilla, :

, , setTimeout(), , .

obj, " ".

+4

obj dismiss() . , . .

+2

:

Code executed by setTimeout() is run in a separate execution context to the function from which it was called. As a consequence, the this keyword for the called function will be set to the window (or global) object; it will not be the same as the this value for the function that called setTimeout.:

- - window.

, obj.style.display , . obj , dismiss, .

, obj - undefined window ( , , ), :

function dismiss(obj) {setTimeout(function ()  { undefined = "none" }, 20);}
+1

:

function dismiss(obj) {setTimeout(obj.style.display = "none", 20);}

' obj.style.display = "none", .

-6

All Articles