通过require.js导出新对象时,它实际上是否创建了“new”对象。对象或只返回现有的实例 [英] While exporting new object via require.js: does it actually create "new" object or just returns an instance of existing

查看:359
本文介绍了通过require.js导出新对象时,它实际上是否创建了“new”对象。对象或只返回现有的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在require.js中有模块A,B和C.模块A导出新对象。

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();   

});

模块B和C从A中导入F()的实例:

Modules B and C imports instance of F() from A:

define(['A'], function(f_inst) {
    // code
});

出于某种原因,我需要F为单身人士。我还没有认真了解require.js的工作原理。所以,这是我的问题:在这种情况下我是否需要为F()使用单例模式?

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?

推荐答案

AMD模块定义 d,只有一次。即使您需要多次,也只会评估一次。

AMD module defined, only once. Even if you require it multiple times, it will be evaluated only once.

您可以查看此示例:

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.

这篇关于通过require.js导出新对象时,它实际上是否创建了“new”对象。对象或只返回现有的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆