javascript中对象内的对象

Mic*_*fen 25 javascript nested object javascript-objects

我对Javascript有些新意,所以也许这只是一个noob错误,但我没有找到任何特别有助于我环顾四周的东西.我正在写一个游戏,我正在尝试为暂停菜单构建一个对象.

我想做的其中一件事是,为了组织起见,菜单上的按钮是pause_menu对象内的对象.我最终要为这些对象添加事件处理程序,我也想在pause_menu对象中执行此操作.有些按钮尚未完全编码,但我希望在继续操作之前至少可以使用一些按钮.

我正在使用Raphael.js v1.5.2渲染形状.拉斐尔的东西适用于界面的其余部分,但是代码并不像这样令人愉快,所以类似的东西对我来说会更好.

我目前的问题是,当我执行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();
Run Code Online (Sandbox Code Playgroud)

好的,所以这是解决方案(使用事件处理程序):

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

};
Run Code Online (Sandbox Code Playgroud)

Jon*_*han 30

var pause_menu = {
    pause_button : { someProperty : "prop1", someOther : "prop2" },
    resume_button : { resumeProp : "prop", resumeProp2 : false },
    quit_button : false
};
Run Code Online (Sandbox Code Playgroud)

然后:

pause_menu.pause_button.someProperty //evaluates to "prop1"
Run Code Online (Sandbox Code Playgroud)

等等

  • 那不是JSON.它们只是对象文字.常见的错误. (9认同)

Joã*_*ira 13

只要将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);
Run Code Online (Sandbox Code Playgroud)

  • @Aónio 无论如何,这都不是什么大问题。IMO 很高兴能够添加新的键值,而不必记住事先添加逗号。(尾随逗号没问题,但忘记用逗号分隔确实是一个错误)。说它通常是“首选”可能是一个过于强烈的说法,也许“常见做法”可能更准确。“首选”听起来比实际情况更重要...... (2认同)