How do I Lock a javascript function to the local scope ? I want to prevent it from using global variables

为君一笑 提交于 2020-01-04 03:18:11

问题


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...


回答1:


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.

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.




回答2:


You could ask your users to restrict themselves to ADsafe code. From the website:

ADsafe makes it safe to put guest code (such as third party scripted advertising or widgets) on a web page. 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. The ADsafe subset can be verified mechanically by tools like JSLint so that no human inspection is necessary to review guest code for safety. The ADsafe subset also enforces good coding practices, increasing the likelihood that guest code will run correctly.

If you tick the right box, JSLint will verify that code is ADsafe-compliant and therefore safe to execute on your site.



来源:https://stackoverflow.com/questions/6083597/how-do-i-lock-a-javascript-function-to-the-local-scope-i-want-to-prevent-it-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!