1

我遵循以下模式在我的项目中使用命名空间:

// simply a namespace attic object
// parent to my worker objects
;(function( RoaringSky, undefined ) 
{
    var opt = {
        backend : ""
    },
    name = ""
    ;

    RoaringSky.init = function( options ) {
       jQuery.extend(opt,options);
       console.log( 'RoaringSky.init complete');
    };
    // accessor 
    RoaringSky.opt = opt;

})(window.RoaringSky = window.RoaringSky || {});

和这个命名空间的一个子对象,所以:

RoaringSky.Day = (function() {

    // constructor
    var Day = function(){

        var id = "none";
        var name = "none";
        var date = "none";
        var periods = new Array();

        this.periods = function() {
            return periods;
        };
    };

    // invoking day.time() fails - is not a function message
    Day.prototype.time = function() {
        return this.doSomthingWithDate(date);
    };


    return Day;
})(window.RoaringSky.Day = window.RoaringSky.Day || {});

我认为,就目前而言,这种模式工作得很好。(欢迎批评)但它似乎阻止了原型属性的使用。

也许我的理解是不完整的(我敢肯定)但是AFAIK,一旦我创建了一个对象 - 就像我上面的 Day 类 - 我应该能够以以下方式编写函数:

Day.prototype.time = function() {
    return this.doSomthingWithDate(date);
};

并且该类的所有实例都将继承该函数,因为它是构造函数的类对象 Day() 的属性;

但是,当我尝试这个时:

var day = new Day();
day = new Date();
console.log( 'day.time: '+ day.time() );

我得到了祝福,“day.time() 不是函数”错误消息。

我究竟做错了什么?这开始让我发疯了。

  • 埃里克
4

1 回答 1

0

几个问题:

RoaringSky.Day = (function() {

    // constructor
    var Day = function(){

        var id = "none";
        var name = "none";
        var date = "none";
        var periods = new Array();

        this.periods = function() {
            return periods;
        };
    };

    // invoking day.time() fails - is not a function message
    Day.prototype.time = function() {
        // can't use "date" here since it is not in scope
        return this.doSomthingWithDate(date);
    };


    return Day;
})(window.RoaringSky.Day = window.RoaringSky.Day || {});

然后:

var day = new Day(); // Day is not a member of window, so this will only work when used in the `RoaringSky.Day` declaration.
day = new Date();    // you then override the day variable for some reason
console.log( 'day.time: '+ day.time() ); // time is not a function member of Date
于 2013-02-14T20:39:06.393 回答