开发者

javascript singleton object per string

I want to create an object which is singleton per a string. For example when I call myObject("string1") it always开发者_开发知识库 returns the same object but different from myObject("string2").


I think you want to do something like this (following your myObject(name) API example):

var myObject = (function (){
  var objects = {
    "myString1": {
      name: "myString One Object"
      //...
    },
    "myString2": {
      name: "myString Two Object"
      //...
    }
  };
  //...
  return function (name) { // the actual function
    return objects[name];  // that retrieves the object
  };                       // by its "name" (e.g. 'myString1')
})();


myObject("myString1").name;  // "myString One Object"
myObject("myString1") === myObject("myString1"); // true, the same object ref.
myObject("myString2").name;  // "myString Two Object"


Create an object with the strings as properties and assign whatever value suits:

var myObject = {
  'string1': ... ,
  'string2': ... ,
  'string3': ... ,
   ...
};

Then access them by the string:

alert( myObject['string1'] ); // whatever


try this

var MyObject = function(){
    var objs = {};

    return function(str){
        if( objs[str] ){
            return objs[str];
        }else{
            objs[str] = function(){
                //some code here
            };
            return objs[str];
        }
    };
}();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜