javascript中对象内部的对象
Objects inside objects in javascript
我对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);
相关文章:
- 访问JSON对象内部的数组元素
- 如何确定对象内部包含对象的JSON的长度
- 正在更新mongod中两个对象内部的数组
- 如何访问对象内部的“categoryIds”字段/键,该对象包含mongodb's `ObjectId(s)`数
- 在javascript中移动对象内部的元素
- 基于使用angular在下拉列表中选择的对象,迭代对象内部的对象
- 如何清除Javascript对象内部的setTimeout
- 为什么数组在对象内部迭代对象时存储重复值
- 我如何使用D3来强制用户点击g.node对象内部的圆形对象
- 正在获取对象内部数组中的对象总数
- 从对象内部调用knockout.js ko.applyBindings()
- 使用ng-src增强对象内部的数组
- 如何在javascript中从对象内部的数组中获取数据
- 对象内部函数内的对象文本的范围
- 在 Forerunner 数据库集合中创建主键时,key 属性是否可以位于集合对象的对象内部
- 如何过滤对象内部深度堆叠的数据(并在之后编辑删除它)
- 对象内部数组中的角度 ng 重复键
- 访问对象内部的数组
- Jhon Papa Angular Style guide Factory-对象内部的函数未运行
- 检查数组中的项是否存在于对象内部