Reputation: 1013
I have this code for a module:
define(
[
"jquery",
],
function
(
$
)
{
this.someArray = []
this.someObject =
function(
someID
somePrivacyType
)
{
this.someID = someID;
this.somePrivacyType = somePrivacyType;
someArray[this.someID] = this;
};
return this;
}
);
And I want to access the above module using it's namespace from another module, but using return this;
throws everything in the global namespace.
like so:
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;
}
);
I would like to continue using some type of return this;
without having to declare the namespace from within the module itself. This way makes it very easy for me to keep private variables by declaring them within the module, but not on this
. I know I could simply declare the namespace from within the module, but this takes away from the modularity.
Is there any way to pull the namespace of the file from RequireJS or some other way to return this
as an object which will be referenced only by the namespace it's being called from?
Upvotes: 0
Views: 65
Reputation: 151511
I suggest the following:
define(["jquery"], function ($) {
var ns = {}; // Create our namespace.
ns.someArray = [];
ns.someObject = function(someID, somePrivacyType) {
this.someID = someID;
this.somePrivacyType = somePrivacyType;
ns.someArray[this.someID] = this;
};
return ns;
});
I'm assuming that ns.someObject
is meant to be called with new
. I've also assumed that your access to someArray
in the function assigned to ns.someObject
is meant to access someArray
on your namespace, hence ns.someArray
.
Depending on the nature of your namespace, you might want to use Object.create(null)
to create it rather than {}
. {}
is okay when you have a finite set of keys and you take care not to override the methods defined on Object
. If not, it is better to use Object.create(null)
to avoid clashes.
Upvotes: 1