See the followingCode:
VaR STR = 'aaa'; var num = 2; function auto (Num) {alert (Num);} setTimeout ('Auto (Num) ', 4000 );
In this way, the write operation works normally, but if it is said that this is a parameter transfer, it is better to say that it is a directly used global variable. Therefore, this writing method is unnecessary. Generally, it is used to pass local variables as parameters.
Modify the Code:
// Var STR = 'aaa'; var num = 2; function test () {var STR = 'bbb'; setTimeout ('Auto (STR) ', 4000 );} function auto (a) {alert (a) ;}test ();
This write method reports an error. If you uncomment the global declaration on STR, AAA is output, that is, the function still calls global variables.
See the following code:
// Var STR = 'aaa'; var num = 2; function test () {var STR = 'bbb'; setTimeout ('Auto ("str ")', 4000);} function auto (a) {alert (a) ;}test ();
Note that the STR above will output "str". That is to say, after the timer calls the function, STR is directly treated as a parameter. The passed parameter is always a string. This is not the expected result.
To pass unexpected parameters except strings, you can use the closure. See the following code:
// Var STR = 'aaa'; var num = 2; function test () {var STR = 'bbb'; setTimeout (Auto (STR), 4000 );} function auto (STR) {return function () {alert (STR) ;}} test ();
The output is 'bbb '. If auto (STR) is enclosed in quotation marks, an error is returned.
Of course, this writing is also good:
VaR num = 2; function test () {var STR = 'bbb'; // setTimeout (Auto (STR), 4000); setTimeout (function () {alert (STR)}, 4000) ;}function auto (STR) {return function () {alert (STR) ;}} test ();
Note that when no closure is used to pass parameters, the function called by the timer must be enclosed by quotation marks. If no quotation marks are provided, an error is returned. The above situations are also suitable for setinterval ();