[英]How do I Lock a javascript function to the local scope ? I want to prevent it from using global variables
Is there a way to prevent a function from using global variables like document
, window
, navigator
, and other declared global functions ? 有没有办法阻止函数使用全局变量,如
document
, window
, navigator
和其他声明的全局函数?
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... 编辑1:如果我可以选择受限制的全局对象,那将是很好的,因为我想允许该函数用作示例Math对象及其函数...
Is there a way to prevent a function from using global variables like document, window, navigator, and other declared global functions?
有没有办法阻止函数使用全局变量,如文档,窗口,导航器和其他声明的全局函数?
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: 想像:
;(function () {
var window = "Hello"
// original content
function foo () {
alert(window)
}
foo()
})()
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. 我之前使用过这个
document
来改变 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. 虽然
with
起初看起来有前途的,重要的是要意识到这仅仅是一个词汇结构以及和不引入动态变量。
Happy coding. 快乐的编码。
You could ask your users to restrict themselves to ADsafe code. 您可以要求您的用户将自己限制为ADsafe代码。 From the website:
来自网站:
ADsafe makes it safe to put guest code (such as third party scripted advertising or widgets) on a web page.
ADsafe可以安全地将访客代码(例如第三方脚本广告或小部件)放在网页上。 ADsafe defines a subset of JavaScript that is powerful enough to allow guest code to perform valuable interactions, while at the same time preventing malicious or accidental damage or intrusion.
ADsafe定义了一个强大的JavaScript子集,允许访客代码执行有价值的交互,同时防止恶意或意外损坏或入侵。 The ADsafe subset can be verified mechanically by tools like JSLint so that no human inspection is necessary to review guest code for safety.
ADsafe子集可以通过JSLint等工具进行机械验证,因此无需人工检查即可查看访客代码的安全性。 The ADsafe subset also enforces good coding practices, increasing the likelihood that guest code will run correctly.
ADsafe子集还实施了良好的编码实践,增加了访客代码正确运行的可能性。
If you tick the right box, JSLint will verify that code is ADsafe-compliant and therefore safe to execute on your site. 如果勾选右侧框, JSLint将验证代码是否符合ADsafe,因此可以安全地在您的站点上执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.