如何将JavaScript函数锁定到本地范围?我想阻止它使用全局变量 [英] How do I Lock a javascript function to the local scope ? I want to prevent it from using global variables

查看:74
本文介绍了如何将JavaScript函数锁定到本地范围?我想阻止它使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以防止函数使用全局变量,如 document window navigator 和其他声明的全局函数?



编辑1:如果我可以选择受限制的全局对象,因为我想允许函数使用Math对象的例子,它的功能...

解决方案



有没有办法阻止函数使用全局变量,如文档,窗口,导航器和其他声明的全局函数?


不,除非......

如果可以修改函数的词法范围 - 也就是说源以某种方式修改,例如将其封装,如下所示。 p>

想象一下:

 ;(function(){
var window =Hello

//原创内容
函数foo(){
alert(window)
}
foo()

))()

这种方法经常用于库中来创建私有名称空间,但,在这些情况下,原始来源也可用并根据此设计。我在 之前使用了文档来修改本地版本的jQuery。



虽然带有的起初看起来很有希望,但重要的是要认识到它只是一个词法结构,并且不会引入动态变量。



快乐编码。

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

解决方案

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.

这篇关于如何将JavaScript函数锁定到本地范围?我想阻止它使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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