How to provide namespaces in JavaScript with instanced objects

后端 未结 5 2072
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  礼貌的吻别
    2021-02-03 11:15

    Both answers were very helpful! Here's what I ended up with:

    if( typeof( rpNameSpace ) == "undefined" ) rpNameSpace = {};
    
    rpNameSpace.foo = function() {
        this.length = 613;
    }
    rpNameSpace.foo.prototype.getLength = function() {
        return this.length * 2;
    }
    

    Then, to use the resulting "namespaced" object:

    var x = new rpNameSpace.foo()
    
    display( x.getLength() );
    

提交回复
热议问题