带有function-prototype的Javascript名称空间声明

Joh*_*lak 18 javascript namespaces class function-prototypes

我知道,这经常被讨论.但在寻找19世纪以外的人之后,我需要一些建议.通过声明"命名空间"我没有问题,但是当涉及到prototype.foo函数时,我卡住了.我找到了一种方法,但我不喜欢它:

Namespace = {}
Namespace.obj = function() {
    this.foo="bar";
}
Namespace.obj.prototype.start = function() {
    this.foo="fubar";
}

blah = new Namespace.obj();
blah.start();
Run Code Online (Sandbox Code Playgroud)

现在,因为我在编写脚本时有点神经质,我想有这样的事情:

Namespace = {
    obj: function() {
        this.foo="bar";
    },
    obj.prototype.start: function(tabinst) {
        this.foo="fubar";
    }
}
...
Run Code Online (Sandbox Code Playgroud)

但随后它会抛出一个错误:"Uncaught SyntaxError:Unexpected token".

我知道,这是装饰性的,但我认为必须有一种更好的方法来声明包含类和原型函数的"命名空间".

Amj*_*sad 34

我这样做的方法是使用"模块模式".
您基本上将所有"模块"逻辑封装在一个自执行函数中,该函数将返回一个包含类,函数,变量等的对象...将返回值视为公开Module API.

Namespace = (function () {
    /** Class obj **/
    var obj = function () {
        this.foo = 'bar';
    };
    obj.prototype = {
        start: function () {
            this.foo = 'fubar';
        }
    };

    /** Class obj2 **/  
    var obj2 = function () {
        this.bar = 'foo'
    };
    obj2.prototype = {
        start: function () {
            this.bar = 'barfoo';
        },
        end: function () {
            this.bar = '';
        }
    };
    return {
        obj : obj,
        obj2: obj2
    };
})();

var o = new Namespace.obj()
o.start()
Run Code Online (Sandbox Code Playgroud)

为了进一步封装"obj"类方法和构造函数,我们可以执行以下操作:

/** Class obj **/
var obj = (function () {
    /** class Constructor **/
    var obj = function () {
        this.foo = 'bar';
    };
    /** class methods **/
    obj.prototype = {
        start: function () {
            this.foo = 'fubar';
        }
    };
    return obj;
})();
Run Code Online (Sandbox Code Playgroud)

还有一个重要的功能是免费使用这种模式,即"私有变量",请考虑以下内容:

/** Class Foo **/
var Foo = (function () {
    // Private variables
    var private_number = 200
    /** class Constructor **/
    var Foo = function () {
        this.bar = 0;
    };
    /** class methods **/
    Foo.prototype = {
        add: function () {
            this.bar += private_number;
        }
    };
    return Foo;
})();

foo = new Foo();
alert(foo.bar); // 0
foo.add(); 
alert(foo.bar);// 200
alert(foo.private_number) //undefined
Run Code Online (Sandbox Code Playgroud)

  • @Johnny如果我理解你的问题,只需在返回对象中添加一个`blah`函数:`..return {obj:obj,obj2:obj2,blah:function(){/*做某事*/}}; (2认同)