While exporting new object via require.js: does it actually create “new” object or just returns an instance of existing

一曲冷凌霜 提交于 2019-12-06 11:50:35

问题


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 defined, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!