2013-02-14 56 views
1

我使用的命名空间在我的项目由folllowing这种模式:使用Javascript命名空间关闭和原型一起失败?

// 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 || {}); 

模式工作正常,只要它去,我想。 (批评欢迎)但它似乎公鸡块使用原型属性。

也许我的理解是不完整的(我敢肯定,这是),但据我所知,有一次我已经创建了一个对象 - 像上面我的天类 - 我应该能够编写函数的方式:

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

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

然而,当我试试这个:

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

我回来了祝福, 'day.time()不是一个函数' 的错误消息。

我在做什么错?这开始让我疯狂。

  • 埃里克
+0

我相信这应该是'VAR天=新RoaringSky.Day();',你也使用'new Date();'覆盖'day','time'不是'Date'对象的函数。 – Shmiddty 2013-02-14 20:36:16

+0

当你做'day = new Date();'时,''Day'上的任何东西都不会保留在'Day'类中。在它上面调用'time'是不会出于同样的原因,当它在'Date'上调用时它不能正常工作。 – 2013-02-14 20:37:13

回答

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