问题描述
我在模块模式之后构造了一个Javascript对象.我有几个私有函数,它们是从其他同级私有"函数中调用的.我该如何访问另一个变量/函数而又不会意外访问全局/外部变量/对象/函数?
I have a Javascript Object structured after the Module Pattern. I have several private function in it which are called from other sibling "private" functions. How can I access another variable/function without the potential to accidentally access a global/external variable/object/function?
function doSomething() {
alert("Something I don't want to do");
}
var My.Namespaced.SingletonClass = (function() {
var init = function() {
doSomething();
}
var doSomething = function() {
alert("Something I want to do");
}
return {
"init": init;
}
})();
My.Namespaced.SingletonClass.init();
我的猜测是,上面的代码实际上将访问正确的内部doSomething
函数,但是我想要的是更多的安全性.我该如何显式地解决内部/嵌套函数,而不必担心意外调用函数或解决我的单例范围内的对象?
My guess is that the above code would in fact access the correct, inner doSomething
function, but I'd like some more security than that. How can I explicitly address the inner/nested function without fear of accidentally calling functions or addressing objects in the scope around my singleton?
推荐答案
简短版本:您不能.如果未将doSomething
定义为init
的同级,则JavaScript会依次搜索范围更广的范围,直到找到doSomething
函数,否则它将用尽搜索范围.
Short version: you can't. If doSomething
isn't defined as a sibling of init
, then JavaScript will search successively broader scopes until it finds a doSomething
function, or it runs out of scopes to search.
长版本:您可以通过使用私有对象来保存您的私有助手功能来防止这种行为,如下所示:
Longer version: you can prevent this sort of behavior by using a private object to hold your private helper functions, like this:
function doSomething() {
alert("Something I don't want to do");
}
// Assuming My.Namespaced is already defined:
My.Namespaced.SingletonClass = (function() {
var helpers = {};
helpers.doSomething = function() {
alert("Something I want to do");
}
var init = function() {
helpers.doSomething();
}
return {
init: init
}
})();
My.Namespaced.SingletonClass.init();
我不确定助手功能是真正的兄弟姐妹是否重要(但是我不明白为什么这特别重要).
I'm not sure if it's important that the helper functions are truly siblings (but I don't see why that would particularly matter).
还请记住,在使用SingletonClass
之前,必须先定义My
和My.Namespaced
-并且无需为返回的对象中的键使用JSON样式的引号.
Also keep in mind that My
and My.Namespaced
need to be defined before you tack on SingletonClass
- and there's no need to use JSON-style quoting for keys in the object you're returning.
这篇关于如何在不访问包含作用域的内容的情况下安全地访问Javascript模块模式中的其他同级函数和变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!