If you want to have two instances of testModule you'll need to return testModule as a function. Then when you require it you can instantiate multiple instances using new
.
Example 1
testModule.js
define([
'jquery'
], function ($) {
function TestModule() {
var self = this;
// anything attached to self or this will be public
self.id = 0;
self.setID = function (newID) {
self.id = newID;
return self.id;
};
}
return TestModule;
});
main.js
require([
"jquery",
"testModule"
], function ($, TestModule) {
$(function () {
var testInstance1 = new TestModule();
var testInstance2 = new TestModule();
testInstance1.setID(11);
testInstance2.setID(99);
alert(testInstance1.id); // Should return 11
alert(testInstance2.id); // Should return 99
});
});
Or if you want to get fancy, you can protect certain properties or functions within testModule.
Example 2
testModule.js
define([
'jquery'
], function ($) {
function TestModule() {
var self = this;
var privateID = 0;
function privateToString() {
return 'Your id is ' + privateID;
}
// anything attached to self or this will be public
self.setID = function (newID) {
privateID = newID;
};
self.getID = function () {
return privateID;
};
self.toString = function () {
return privateToString();
};
}
return TestModule;
});
main.js
require([
"jquery",
"testModule"
], function ($, TestModule) {
$(function () {
var testInstance1 = new TestModule();
var testInstance2 = new TestModule();
testInstance1.setID(11);
testInstance2.setID(99);
alert(testInstance1.getID()); // Should return 11
alert(testInstance2.getID()); // Should return 99
alert(testInstance1.privateID); // Undefined
alert(testInstance1.toString()); // Should return "Your id is 11"
});
});
If you just want a single instance like a singleton you can return TestModule using the new
keyword.
Example 3
testModule.js
define([
'jquery'
], function ($) {
function TestModule() {
var self = this;
// anything attached to self or this will be public
self.id = 0;
self.setID = function (newID) {
self.id = newID;
return self.id;
};
}
return new TestModule();
});
main.js
require([
"jquery",
"testModule"
], function ($, testModule) {
$(function () {
var testInstance1 = testModule;
var testInstance2 = testModule;
testInstance1.setID(11);
testInstance2.setID(99);
alert(testInstance1.id); // Should return 99
alert(testInstance2.id); // Should return 99
});
});