testModuleのインスタンスを2つ作成する場合は、testModuleを関数として返す必要があります。次に、必要に応じて、を使用して複数のインスタンスをインスタンス化できますnew
。
例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
});
});
または、凝ったものにしたい場合は、testModule内の特定のプロパティまたは関数を保護できます。
例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"
});
});
シングルトンのような単一のインスタンスが必要な場合は、new
キーワードを使用してTestModuleを返すことができます。
例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
});
});