如果您想拥有两个 testModule 实例,则需要将 testModule 作为函数返回。然后,当您需要它时,您可以使用new
.
示例 1
测试模块.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
测试模块.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
测试模块.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
});
});