2013-02-14 31 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