如何从内部访问外部属性?

时间:2011-06-28 12:37:29

标签: javascript

嗨,我想模仿一个书柜。我的问题是如何从对象内部方法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]);
}

1 个答案:

答案 0 :(得分:0)

尝试将属性定义为内部变量,然后您可以创建一个属性,如果您愿意,可以返回该变量

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

并添加

if(Max_Width > Width)