setTimeout(function() {alert('outer ' + test)}, 0); // 输出 outer in the window ,默认在window的全局作用域下
functionf() { var test = 'in the f!'; // 局部变量,window作用域不可访问 setTimeout('alert("inner " + test)', 0); // 输出 inner in the window, 虽然在f方法的中调用,但执行代码(字符串形式的代码)默认在window全局作用域下,test也指向全局的test }
setTimeout(function() {alert('outer' + test)}, 0); // outer in the window ,没有问题,在全局下调用,访问全局中的test
functionf() { var test = 'in the f!'; setTimeout(function(){alert('inner '+ test)}, 0); // inner in the f! 有问题,不是说好了执行函数中的this指向的是window吗?那test也应该对应window下 // 的值才对,怎么test的值却是 f()中的值呢???? }
f();
<!-- 等价于 --> var test = "in the window";
setTimeout(function() {alert('outer ' + test)}, 0); // in the window