【发布时间】:2013-08-09 15:27:34
【问题描述】:
在阅读了reply 对我对链接帖子的评论后,我决定对window 对象和全局范围进行测试。我阅读了一些关于如何引用原始函数的其他问题,例如 this、this 和 this,但它们通常都涉及将原始函数存储在另一个变量中或将其包装在匿名函数中(单独的命名空间) .
测试代码
var x = ' 0 '; // a global variable
document.body.innerHTML += x;
document.body.innerHTML += window.x;
// setTimeout before overriding
setTimeout(function () {
document.body.innerHTML += ' 1 ';
}, 500);
// window.setTimeout before overriding
window.setTimeout(function() {
document.body.innerHTML += ' 2 ';
}, 1000);
// Overriding setTimeout
function setTimeout(f, time) {
'use strict';
if (typeof f === 'function') {
document.body.innerHTML += ' 3 ';
}
}
// setTimeout after overriding
setTimeout(function () {
document.body.innerHTML += ' 4 ';
}, 1000);
// window.setTimeout after overriding setTimeout globally
window.setTimeout(function () {
document.body.innerHTML += ' 5 ';
}, 2000);
// Overriding window.setTimeout
window.setTimeout = function (f, time) {
'use strict';
if (typeof f === 'function') {
document.body.style.backgroundColor = 'orange';
}
};
// window.setTimeout after overriding
window.setTimeout(function () {
document.body.innerHTML += ' 6 ';
}, 3000);
见jsFiddle。请注意,在小提琴初始化后,您可能需要点击 Run 才能看到延迟。
实验结果
0
undefined
3
3
(page becomes orange)
2 (after a delay)
5 (after a longer delay)
预期结果
0
0
3
(page becomes orange)
1 (after 500ms)
2 (after 1000ms)
5 (after 2000ms)
谁能解释为什么我的代码的行为与预期不同?
另外,我意识到在浏览器环境之外运行的 JavaScript 会有所不同,因此出于这个问题的目的,我将只关注浏览器环境中的 JavaScript 应用程序。
【问题讨论】:
-
我出名了!哈哈,我觉得你真的把它从 cmets 中拿出来提出了一个问题,而不是争论它或只是驳回它,这很酷
标签: javascript scope global