是否有充分的理由将字符串传递给setTimeout? [英] Is there ever a good reason to pass a string to setTimeout?

查看:104
本文介绍了是否有充分的理由将字符串传递给setTimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道将字符串传递给 setTimeout (或 setInterval )是邪恶的,因为它是在全局范围,有性能问题,如果你注入任何参数等可能是不安全的。所以这样做肯定是弃用的:

We all know that passing a string to setTimeout (or setInterval) is evil, because it is run in the global scope, has performance issues, is potentially insecure if you're injecting any parameters, etc. So doing this is definitely deprecated:

setTimeout('doSomething(someVar)', 10000);

赞成此:

setTimeout(function() {
    doSomething(someVar);
}, 10000);

我的问题是:有没有理由去做前者?它永远更可取吗?如果不是,为什么它甚至被允许?

My question is: can there ever be a reason to do the former? Is it ever preferable? If it isn't, why is it even allowed?

我想到的唯一场景是想要使用全局范围内存在的函数或变量但已在当地范围内被覆盖。这听起来像是糟糕的代码设计,但是......

The only scenario I've thought of is of wanting to use a function or variable that exists in the global scope but has been overridden in the local scope. That sounds to me like poor code design, however...

推荐答案

你总是可以通过访问它们作为属性来使用全局变量window对象,比如 window.globalVar (虽然使用全局变量确实不是一个好习惯),所以不,我认为没有充分的理由使用不推荐使用语法。

You can always use global variables by accessing them as properties of the window object, like window.globalVar (though using globals is indeed not a good practice), so no, I don't think there is ever a good reason to use the deprecated syntax.

可能由于历史原因而允许:正如Felix Kling所提到的,原始语法只允许传递一串代码:

It is probably allowed for historical reasons: as Felix Kling mentioned, the original syntax did only allow to pass a string of code:


引入JavaScript 1.0,Netscape 2.0。 使用JavaScript 1.2,Netscape 4.0 引入了传递Function对象引用;自5.0版以来由MSHTML DOM支持。 [来源,我的重点]

Introduced with JavaScript 1.0, Netscape 2.0. Passing a Function object reference was introduced with JavaScript 1.2, Netscape 4.0; supported by the MSHTML DOM since version 5.0. [source, my emphasis]

如果浏览器不支持使用字符串作为 setTimeout setInterval <的第一个参数/ code>不再,互联网上会有很多代码不再起作用。

If browsers don't support the use of a string as first argument to setTimeout and setInterval anymore, there will be lots of code on the internet that doesn't function anymore.

这篇关于是否有充分的理由将字符串传递给setTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆