如何将 javascript 函数锁定到本地范围?我想阻止它使用全局变量
有没有办法阻止函数使用全局变量,例如 document
、window
、navigator
和其他声明的全局函数?
EDIT1:如果我可以选择受限制的全局对象,那就太好了,因为我想允许该函数使用 Math 对象及其函数作为示例......
Is there a way to prevent a function from using global variables like document
, window
, navigator
, and other declared global functions ?
EDIT1: And if I could choose which global objects that are restricted it would be great, because I would like to allow the function to use for an example the Math object and it's functions...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,除非...
完成此任务的唯一方法是可以更改函数的词法范围——也就是说,修改源代码 以某种方式,例如如下所示包装它。
想象一下:
这种方法经常在库中用于创建私有名称空间,但在这些情况下,原始源也是可用的,并且在设计时就考虑到了这一点。我之前曾将其与
document
一起使用来更改本地版本的 jQuery。虽然
with
乍一看可能看起来很有希望,但重要的是要认识到它也只是一个词法结构,并且不引入动态变量。快乐编码。
No, unless...
The only way this task is possible is if the lexical scope of the functions can be altered -- that is, the source is modified in some way, such as wrapping it as shown below.
Imagine:
This approach is used often in libraries to create private namespaces but, in those cases, the original source is also available and designed with this in mind. I have used this with
document
before to alter a local version of jQuery.While
with
might look promising at first, it is important to realize it is only a lexical construct as well and does not introduce dynamic variables.Happy coding.
您可以要求用户限制使用 ADsafe 代码。来自网站:
如果您勾选右侧的框,JSLint 将验证代码是否符合 ADsafe,因此可以在您的网站上安全执行。
You could ask your users to restrict themselves to ADsafe code. From the website:
If you tick the right box, JSLint will verify that code is ADsafe-compliant and therefore safe to execute on your site.