如何在javascript中基于参数创建对象的单例实例

How to create singleton instances of object based on a parameter in javascript?

本文关键字:参数 创建对象 实例 单例 javascript 于参数      更新时间:2023-09-26

我需要创建一个对象的单例实现,如果它的参数(例如,doc_id)保持不变,则只返回相同的对象,否则如果doc_id改变,则创建一个具有doc_id属性的新实例。

,

var object;
function mysingletonObj(obj){
    obj = obj || {};
    object.doc_id = obj.doc_id || 'default';
    object.timeoutDuration = obj.timeoutDuration || 3000;
    // i need to return a new object if obj.doc_id is new and there is
    // no other instace of Object with same doc_id otherwise return
    // that instance with same doc_id
    return{
       getInstance: if(!object){
         return object;
       }
     }
}
var Singleton = (function () {
    var instance;
    var parameter;
    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }
    return {
        getInstance: function (doc_id) {    
            if (!instance || doc_id !== parameter) {
                instance = createInstance();
                parameter = doc_id;
            }
            return instance;
        }
    };
})();

var instance1 = Singleton.getInstance(doc_id);