JavaScript闭包内的Namespaced对象初始化

时间:2015-04-09 16:35:15

标签: javascript

我从http://frugalcoder.us/post/2010/02/11/js-classes.aspx获取了此片段:

if (typeof My == 'undefined')
My = {};
if (typeof My.Namespace == 'undefined')
My.Namespace = {};
//begin private closure
(function(){

    //this is a private static member that is only available in this closure
    var instances = 0;

    //this is a private static method that can be used internally
    function _incrementInstances() {
        instances++;
    }

    //Define SomeClass (js uses functions as class constructors, utilized with the "new" keyword)
    this.SomeClass = function(options) {
        //if the function is called directly, return an instance of SomeClass
        if (!(this instanceof SomeClass))
            return new SomeClass(options);

        //call static method
        _doSomething();

        //handle the options initialization here
    }

    //create a public static method for SomeClass
    this.SomeClass.getInstanceCount = function() {
        return instances; //returns the private static member value
    }

    //create an instance method for SomeClass
    this.SomeClass.prototype.doSomething = function() {
        /*Do Something Here*/
    }

//end private closure then run the closure, localized to My.Namespace
}).call(My.Namespace);

然后,在document.ready回调中,两者:

$(function () {
   My.Namespace.SomeClass({});
});

$(function () {
   new My.Namespace.SomeClass({});
});

给出以下错误:

Uncaught ReferenceError: SomeClass is not defined

我错过了什么?我想也许是因为教程很旧(2010)?

提前致谢!

1 个答案:

答案 0 :(得分:1)

代码完全不正确。但它可以修复:

this.SomeClass = function SomeClass(options) { // <--- Name the function
    //if the function is called directly, return an instance of SomeClass
    if (!(this instanceof SomeClass))
        return new SomeClass(options);

    //call static method
    _doSomething();

    //handle the options initialization here
}

通过给函数赋予这样的名称,符号“SomeClass”将在函数内部作为参考(对自身)。

请注意,_doSomething也没有定义,构造函数实际上并没有调用那个计算实例的函数。