我知道您可以创建带有子对象和函数的文字对象:
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 中使用子方法?
--编辑--
我的目标是创建一个类,我可以使用它在屏幕中间显示一个框,用于显示消息、问题(以获得是/否响应)和表单。我在想一种构造它的好方法是使用子方法,这样它就可以被引用:
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();
--编辑-- 谢谢@Sean Vieira
为了完整起见,我将使用他的解决方案将我的代码修改版本放在这里:
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
最佳答案
你可以通过链接轻松地做到这一点
function Box() {
this.show = function(){
//your code goes here
return this;
},
this.message = function(message){
//code goes here
return this;
}
}
var aBox = new Box();
aBox.message('the message').show()
关于javascript - javascript中的子对象函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6232444/