javascript中对象内部的对象

Objects inside objects in javascript

本文关键字:对象 内部 javascript      更新时间:2023-09-26

我对Javascript有点陌生,所以这可能只是一个小错误,但我在四处寻找时没有发现任何特别帮助我的东西。我正在写一个游戏,我正试图为暂停菜单构建一个对象。

为了组织起见,我想做的一件事是让菜单上的按钮成为pause_menu对象中的对象。我最终将向这些对象添加事件处理程序,我也希望在pause_menu对象中这样做。有些按钮还没有完全编码,但在继续操作之前,我想至少做一些工作。

我使用Raphael.js v1.5.2来渲染形状。Raphael的东西适用于界面的其余部分,但它的代码并不像这个那样令人愉快,所以类似的东西对我来说更可取。

我目前的问题是,当我执行var pause_menu=new pause_mnu()时,实际上没有任何渲染;

这是我到目前为止为暂停菜单准备的代码:

//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();

好的,下面是解决方案(使用事件处理程序):

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: {}
};
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"

等等。

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

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