如何在同一命名空间内从函数B调用函数A? [英] How to call function A from function B within the same namespace?
问题描述
假设我有命名空间,
var Namespace = {
A : function() {
alert('Hello!');
},
B : function() {
// Call A() from here, do other stuff
}
}
在这个命名空间中,我打算让A成为B的辅助函数。也就是说,A()永远不会在外面调用命名空间。它只会被命名空间中的函数调用。
In this namespace, I intend for A to be a helper function to B. That is to say, A() will never be called outside the namespace. It will only be called by the functions within the namespace.
解决命名空间中本地/辅助函数问题的最佳方法是什么?我看到的方式有两种可能:
What's the best way to address the issue of a local/helper function within a namespace? The way I see it there are two possibilities:
// Method #1
var Namespace = {
A: function() {
alert('Method #1');
},
B : function() {
Namespace.A();
}
}
Namespace.B();
// Method #2
function Namespace2() {
var A = function() {
alert('Method #2');
};
this.B = function() {
A();
}
}
var ns2 = new Namespace2();
ns2.B();
在第一种方法中,输入Namespace.A()(重复)是很丑陋和笨拙的命名空间中的每个函数。这使我更喜欢方法#2。但我很好奇这里最好的做法是什么。
In the first method, it is ugly and awkard to type Namespace.A() (repeatedly) in every function within the namespace. This leads me to prefer Method #2. But I was curious what was the best practice here.
推荐答案
我建议将命名空间放在函数范围内。一切未明确公开的内容将自然是私有的:
I recommend placing the "namespace" inside a function scope. Everything not explicitly public will be naturally private:
var Namespace = (function() {
var self = {};
// Private
var A = function() {
...
};
// Public
self.B = function() {
A();
}
return self;
}());
Namespace.B(); // Works
Namespace.A(); // Doesn't work
这篇关于如何在同一命名空间内从函数B调用函数A?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!