问题
Let's assume I have modules A, B and C in require.js. Module A export new object.
define(function() {
// constructor
function F() {
this.prop = 'some';
}
// module exports
return new F();
});
Modules B and C imports instance of F() from A:
define(['A'], function(f_inst) {
// code
});
For some reason I need F to be singleton. I have not serious understanding of how require.js works. So, this is my question: do I need to use singleton patterns for F() in this case?
回答1:
AMD module define
d, only once. Even if you require it multiple times, it will be evaluated only once.
You may checkout this example:
F.js
define(function() {
// constructor
function F() {
this.prop = 'some';
}
// module exports
console.log('evaluated!');
return new F();
});
A.js
define(['./F'], function(F) {
return 'A';
});
B.js
define(['./F'], function(F) {
return 'B';
});
main.js
require(['./A', './B'], function(A, B) {
console.log(A, B);
});
index.html
<!doctype html>
<html>
<head>
</head>
<body>
<script data-main="main" src="require.js"></script>
</body>
</html>
'evaluated' message printed only once.
来源:https://stackoverflow.com/questions/21218787/while-exporting-new-object-via-require-js-does-it-actually-create-new-object