我知道您可以使用子对象和函数创建文字对象:
var obj = {
val : 1,
level1 : {
val : 2,
val2 : 3,
func : function(){
return this.val2
}
}
}
console.log(obj.val);
console.log(obj.level1.val);
console.log(obj.level1.func());
输出:
1
2
3
我想做的是对对象中的方法做同样的事情,类似于:
function objType() {
this.val = 1;
this.func = function(){
return this.val;
}
this.level1 = function(){
this.val = 2;
this.func = function(){
return this.val;
}
this.level2 = function(){
this.val = 3;
this.func = function(){
return this.val;
}
}
};
};
那么我期望:
var obj = new objType();
console.log(obj.func());
console.log(obj.level1.func());
console.log(obj.level1.level.func());
输出:
1
2
3
但是,在脚本引发错误之前,仅输出第一个 console.log。
Javascript 有什么办法可以有子方法吗?
--edit--
我的目标是创建一个类,我可以使用它在屏幕中间显示一个框,用于显示消息、问题(以获得是/否响应)和表单。我正在考虑使用子方法来构建它的好方法,以便可以通过以下方式引用它:
function box() {
this.show = function(){
//multiple sub methods here
}
this.hide = function(){
//code to hide window here
}
}
var aBox = new box();
aBox.show.message('the message');
aBox.hide();
aBox.show.question('the question');
aBox.hide();
- 编辑 -
谢谢@肖恩·维埃拉
为了完整起见,我将使用他的解决方案将代码的修改版本放在这里:
function objType() {
this.val = 1;
this.func = function(){
return this.val;
}
this.level1 = {
val : 2,
func : function(){
return this.val;
},
level2 : {
val : 3,
func : function(){
return this.val;
}
}
}
var obj = new objType();
console.log(obj.func());
console.log(obj.level1.func());
console.log(obj.level1.level.func());
输出
1
2
3