2011-06-28 55 views
0

嗨,我想模仿書櫃。我的問題是如何從內部對象方法Add()中訪問this.MAX_WIDTH ...? :-(怎麼樣?如何從內部訪問外部屬性?

function bookCase(){ 
    this.bcname="new Book Case 1"; 
    this.showName=function(){return this.name;} 
    this.MAX_WIDTH=50;  // 0 for unlimited :-) 
    this.MAX_HEIGHT=0;  // Unlimited by default :-) 
    this.MAX_SHELVES=0;   // Unlimited No. of Shelves by Default :-) 
    this.currrWidth = 0;  // Nothing Kept Yet :-) 
    this.currrHeight= 0;  // Nothing Kept Yet :-) 
    this.currWidth=0; 


    this.showCapacity = function(MW,MH,MS){ 
         var ReturnVal=""; 
         if(MW){ if(ReturnVal!="") 
          { 
           ReturnVal =","+ ReturnVal + this.MAX_WIDTH; 

          } else { 
            ReturnVal = ReturnVal + this.MAX_WIDTH; 

           } 
         } 
         if(MH){ if(ReturnVal!="") 
          { 
           ReturnVal = ReturnVal + "," + this.MAX_HEIGHT; 
          } else {ReturnVal = ReturnVal + this.MAX_HEIGHT;} 
         } 
         if(MS){ if(ReturnVal!="") 
          { 
           ReturnVal = ReturnVal + "," + this.MAX_SHELVES; 
          } else {ReturnVal = ReturnVal + this.MAX_SHELVES;} 
         } 
         if(!MW&&!MH&&!MS){return this.MAX_WIDTH + "," + this.MAX_HEIGHT + "," + this.MAX_SHELVES;} 

         return ReturnVal; 
        } 
    this.shelf = 
    { 
     books : new Array(), 
     book : 
     { 
      add : function(Place,Width) 
      { 
       if(window.bookCase.MAX_WIDTH > Width) 
       { 
        this.books[Place]=Width; alert("book Added"); 
       } 
       else {alert("No Space In BookShelf: Max Width is "+window.bookCase.MAX_WIDTH); alert(window.bookCase.bcname);} 

      } 
     } 


    } 

} 

var bookStack = new Array(); 
    bookStack[0] = 10; 
    bookStack[1] = 20; 
/* bookStack[2] = 20; 
    bookStack[3] = 10; 
    bookStack[4] = 10; 
    bookStack[5] = 10; 
    bookStack[6] = 10; 
    bookStack[7] = 10; 
    bookStack[8] = 10; 
    bookStack[9] = 10; 
    bookStack[10] = 10; 

*/ 
var foo = new bookCase; 
var LC =0; 

for(LC=0;LC<=bookStack.length;LC++) 
{ 
    foo.shelf.book.add(LC,bookStack[LC]); 
} 
+0

什麼語言是這樣的嗎?它看起來並不像你在定義一個對象。它看起來更像是一個函數。 – Andrew

+0

@Andrew它的javascript。 –

+0

@Daniel - 這樣更合理...... – Andrew

回答

0

嘗試定義你的屬性內部變量,那麼你就可以創建一個返回變量,如果你喜歡

function bookCase(){ 
var Max_Width =50; 
this.MAX_WIDTH=Max_width;  // 0 for unlimited :-) 

,並添加屬性

if(Max_Width > Width) 
+0

太棒了!現在我會輕鬆地做到這一點,我會重寫所有的對象,然後我會在這裏發佈它。 –

+0

不用客氣:)如果能解決問題,你能接受嗎? – Doga