How to provide namespaces in JavaScript with instanced objects

后端 未结 5 2077
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 10:42

I\'ve got a JavaScript \"object\", built this way:

function foo()
{
    this.length = 0;
}

foo.prototype.getLength = function()
{
    return this.length;
}

...         


        
5条回答
  •  梦毁少年i
    2021-02-03 11:09

    Javascript doesn't really have namespace or packages like other languages. Instead it has closures. If you have an application that consists of multiple functions, variables and objects, then you should put them inside a single global object. This will have the same effect as a namespace.

    For example:

    var namespace = {
      this.foo: function(){
        ...
      },
      this.foo.prototype.getLength: function(){
        ...
      }
    }
    

    You could also create a set of nested objects and simulate packages:

    loadPackage = function(){
      var path = arguments[0];
      for(var i=1; i

提交回复
热议问题