2011-06-21 114 views
14

我对JavaScript有点新,所以也许这只是一个noob错误,但我没有找到任何特别帮助我,而环顾四周。我正在编写一个游戏,并且正在尝试为暂停菜单构建一个对象。javascript中的对象内部的对象

我想要做的一件事是让菜单上的按钮成为pause_menu对象内部的对象,以便组织。我最终要为这些对象添加事件处理程序,并且我也想在pause_menu对象内部执行此操作。有些按钮还没有完全编码,但我希望在继续之前至少得到一些工作。

我使用Raphael.js v1.5.2来呈现形状。 Raphael的东西适用于接口的其余部分,但代码并不像看起来那么愉快,所以类似这样的东西比我更喜欢。

我目前的问题是,当我做var pause_menu = new pause_menu();

这是我至今对暂停菜单代码:

//Pause Menu Object: 
function pause_menu() { 

    function pause_button() { 
     this.button = game.rect(0, 350, 150, 50, 5); 
     this.text = game.text(75, 375, 'PAUSE'); 
    } 
    function resume_button() { 
     this.button; 
     this.text; 
    } 
    function quit_button() { 
     this.button; 
     this.text; 
    } 
    this.pause_button = new pause_button(); //the button that the user presses to pause the game (I want an event handler on this to trigger .show() method for presently hidden menu items) 
    this.resume_button = new resume_button(); 
    this.quit_button = new quit_button(); 
    this.box = game.rect(150, 50, 400, 300, 5).hide(); //the box that surrounds the menu when it appears 
} 
var pause_menu = new pause_menu(); 

OK,所以这里的解决方案(与事件处理程序):

var pause_menu = { 

    pause_button: { button : game.rect(0, 350, 150, 50, 5).click(function (event){ 
         pause_menu.menu_box.show(); 
        }), text : game.text(75, 375, 'PAUSE') }, 
    menu_box: game.rect(150, 50, 400, 300, 5).hide(), 
    resume_button: {}, 
    quit_button: {} 

}; 
+0

不知道在哪里的问题是没有代码的其余部分,但要注意,你在执行'var pause_menu = new pause_menu();'时,覆盖您的'pause_menu'函数与函数在同一个变量范围内。 – user113716

+0

感谢帕特里克,在实际的游戏'var pause_menu = new pause_menu();'与功能不在同一范围。是否覆盖,因为变量的名称与函数相同? –

+0

看起来好像你需要创建一个呈现game.rect()实例的render()方法? –

回答

18
var pause_menu = { 
    pause_button : { someProperty : "prop1", someOther : "prop2" }, 
    resume_button : { resumeProp : "prop", resumeProp2 : false }, 
    quit_button : false 
}; 

则:

pause_menu.pause_button.someProperty //evaluates to "prop1" 

等等

+9

这不是JSON。他们只是对象文字。常见的错误。 – user113716

+0

这个和兰斯答案的结合解决了这个问题,谢谢你们! –

3

只要将对象声明为另一个父对象的属性,就可以拥有尽可能多的对象层次结构。注意每个级别的逗号,这是棘手的部分。每个级别上的最后一个元素之后不要使用逗号:

{el1, el2, {el31, el32, el33}, {el41, el42}}

var MainObj = { 
 

 
    prop1: "prop1MainObj", 
 
    
 
    Obj1: { 
 
    prop1: "prop1Obj1", 
 
    prop2: "prop2Obj1",  
 
    Obj2: { 
 
     prop1: "hey you", 
 
     prop2: "prop2Obj2" 
 
    } 
 
    }, 
 
    
 
    Obj3: { 
 
    prop1: "prop1Obj3", 
 
    prop2: "prop2Obj3" 
 
    }, 
 
    
 
    Obj4: { 
 
    prop1: true, 
 
    prop2: 3 
 
    } 
 
}; 
 

 
console.log(MainObj.Obj1.Obj2.prop1);