【发布时间】:2014-03-04 10:29:54
【问题描述】:
我有这个模块的代码:
define(
[
"jquery",
],
function
(
$
)
{
this.someArray = []
this.someObject =
function(
someID
somePrivacyType
)
{
this.someID = someID;
this.somePrivacyType = somePrivacyType;
someArray[this.someID] = this;
};
return this;
}
);
我想从另一个模块使用它的命名空间来访问上面的模块,但是使用return this; 会在全局命名空间中抛出所有内容。
像这样:
define(
[
"jquery",
"myProject/SomeModule"
],
function
(
$,
SomeModule
)
{
console.log(SomeModule); //Returns window
//someArray is in the global namespace rather than only
console.log(someArray); //Returns someArray (Want it to return undefined)
//on the SomeModule namespace below
console.log(SomeModule.someArray); //Returns someArray (Want only this to return Array)
console.log(SomeModule.someObject);
return this;
}
);
我想继续使用某种类型的return this;,而不必在模块本身内声明命名空间。这种方式使我很容易通过在模块中声明私有变量来保留私有变量,而不是在this 上。我知道我可以简单地从模块中声明命名空间,但这会破坏模块化。
有什么方法可以从 RequireJS 中提取文件的命名空间,或者以其他方式将 this 作为对象返回,该对象只能被调用它的命名空间引用?
【问题讨论】:
标签: javascript module namespaces dependencies requirejs