1

is there a way to define global namespace, so that i can call function from this namespace from all my page?

e.g

// in one file i define below code

DefineNameSpace("my.namespace.api", { 
    addObject: function(obj) {
         // store obj into indexDB
    },
    readAllObject: function() {
         // return array of object from indexdb
    }
})

// so that in another javascript file i can do

my.namespace.api.addObject({name: "foo", desc: "bar"});

is there a way to implement "DefineNameSpace" method?

Thanks

4

2 回答 2

3

一种非常简单的方法是:

my = {
   namespace: {
      api : {}
   }
}

my.namespace.api.addObject = function (obj) { }

您实际上是在创建对象,但这样它也可以用作命名空间:)

嗯,这不是您正在实施的方法。但是使用方法构建命名空间需要在加载脚本文件之前调用该函数,否则在调用 DefineNamespace 方法之前调用这些代码行,您将遇到命名空间的一部分在那一点上是未定义的。使用上述解决方案,情况并非如此,尽管不幸的是它不是动态的。

于 2013-08-09T07:15:28.153 回答
1

动态构建命名空间可以通过以下方式完成:

// the root of the namespace would still be handy to have declared here
var my = {};

function defineNamespace(namespaceStr) {
   var namespaceSegments = namespaceStr.split(".");
   var namespaceSoFar = null;

   // iterate through namespace parts
   for (var i = 0; i < namespaceSegments.length; i++) {
      var segment = namespaceSegments[i];

      if (i == 0) {
          // if namespace starts with my, use that
          if (segment == "my") { 
              // set pointer to my
              namespaceSoFar = my;
          }
          else {
          // create new root namespace (not tested this, but think this should work)
              var otherNamespace = eval(segment);
              if (typeof otherNamespace == "undefined") {
                 eval(segment + " = {};");
              }
              // set pointer to created root namespace
              namespaceSoFar = eval(segment);
          }  
      }
      else {
          // further build the namespace
          if (typeof namespaceSoFar[segment] == "undefined") {
              namespaceSoFar[segment] = {};
          }
          // update the pointer (my -> my.namespace) for use in the next iteration
          namespaceSoFar = namespaceSoFar[segment];
      }
   }
}
于 2013-08-09T07:37:21.467 回答