重写 javascript 中的全局函数
我正在尝试将自己的错误处理添加到 JavaScript setTimeout 函数中。以下代码在 chrome 中运行良好:
var oldSetTimeout = window.setTimeout;
window.setTimeout = function setTimeout(func, delay) {
var args = Array.prototype.slice.call(arguments, 0);
args[0] = function timeoutFunction() {
var timeoutArgs = Array.prototype.slice.call(arguments, 0);
try {
func.apply(this,timeoutArgs);
}
catch (exception) {
//Do Error Handling
}
}
return oldSetTimeout.apply(this, args);
}
但在 IE7 中它变成了递归函数。由于某种原因,oldSetTimeout
被设置为新函数。
有什么建议吗?
side note: Yes, I need to do it this way. I am using a pile of 3rd party libraries all of which don't deal with setTimeout well, so I can't just change the calls to setTimeout.
I am trying to add my own error handling to the JavaScript setTimeout function. The following code works fine in chrome:
var oldSetTimeout = window.setTimeout;
window.setTimeout = function setTimeout(func, delay) {
var args = Array.prototype.slice.call(arguments, 0);
args[0] = function timeoutFunction() {
var timeoutArgs = Array.prototype.slice.call(arguments, 0);
try {
func.apply(this,timeoutArgs);
}
catch (exception) {
//Do Error Handling
}
}
return oldSetTimeout.apply(this, args);
}
But in IE7 it turns into a recursive function. For some reason oldSetTimeout
gets set to the new function.
Any suggestions?
side note: Yes, I need to do it this way. I am using a pile of 3rd party libraries all of which don't deal with setTimeout well, so I can't just change the calls to setTimeout.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您使用的是命名函数表达式,而这些表达式在 IE 中的实现不正确。删除函数名称将解决眼前的问题。请参阅 kangax 的
一般来说,尝试覆盖宿主对象的属性(例如
window
、document
或任何 DOM 元素)并不是一个好主意,因为无法保证环境允许它。宿主对象不受与本机对象相同的规则的约束,并且本质上可以做它们想做的事。也不能保证主机方法将是Function
对象,因此oldSetTimeout
可能并不总是具有apply()
方法。 IE 中就是这种情况,因此调用oldSetTimeout.apply(this, args);
将不起作用。我建议改为以下内容:
This is because you're using named function expressions, which are incorrectly implemented in IE. Removing the function names will fix the immediate problem. See kangax's excellent article on this subject. However, there's another problem that isn't so easily fixed.
In general, it's not a good idea to attempt to override properties of host objects (such as
window
,document
or any DOM element), because there's no guarantee the environment will allow it. Host objects are not bound by the same rules as native objects and in essence can do what they like. There's also no guarantee that a host method will be aFunction
object, and henceoldSetTimeout
may not have always have anapply()
method. This is the case in IE, so the call tooldSetTimeout.apply(this, args);
will not work.I'd suggest the following instead:
对 Tim Down 的答案进行了小幅改进,以更多地模仿原始内容:
Minor improvement to the Answer of Tim Down to mimic the original even more: