javascript中的多个嵌套函数
我是一个javascript项目的后台工程,需要在一些已经编写好的代码中注入一个函数 我希望能够在javascript中调用如下函数: 人。口。喊(字) 因此,这将调用使对象“hout”的函数 我的问题是,如何创建人类对象的子属性。据我所知,javascript中只能有一个嵌套函数,因此最基本的情况是:javascript中的多个嵌套函数,javascript,oop,Javascript,Oop,我是一个javascript项目的后台工程,需要在一些已经编写好的代码中注入一个函数 我希望能够在javascript中调用如下函数: 人。口。喊(字) 因此,这将调用使对象“hout”的函数 我的问题是,如何创建人类对象的子属性。据我所知,javascript中只能有一个嵌套函数,因此最基本的情况是: function HumanObj(){ this.shout = function(word){ alert(word); } } 那么,我将使用以下方法来称
function HumanObj(){
this.shout = function(word){
alert(word);
}
}
那么,我将使用以下方法来称呼它:
var human = new HumanObj;
human.shout("HELLO WORLD");
所以这会给我们一个警告:“你好,世界”
那么,我该如何分解它,这样我就可以用下面的公式来调用它了
var human = new HumanObj;
human.mouth.shout("HELLO WORLD");
已经尝试过这个,但没有成功-假设您不能有太多级别的嵌套函数
function HumanObj(){
this.mouth = function(){
this.shout = function(word){
alert(word);
}
}
}
谢谢 您可以执行以下操作:
function HumanObj(){
this.mouth = {
shout: function(word){
alert(word);
}
};
}
function HumanObj(){
function mouthObj() {
this.shout = function(word){
alert(word);
}
}
this.mouth = new mouthObj();
}
或者,如果您需要mouth
可实例化(原型中包含其他内容),您可以执行以下操作:
function HumanObj(){
this.mouth = {
shout: function(word){
alert(word);
}
};
}
function HumanObj(){
function mouthObj() {
this.shout = function(word){
alert(word);
}
}
this.mouth = new mouthObj();
}
你可以做:
function HumanObj(){
this.mouth = {
shout: function(word){
alert(word);
}
};
}
function HumanObj(){
function mouthObj() {
this.shout = function(word){
alert(word);
}
}
this.mouth = new mouthObj();
}
或者,如果您需要mouth
可实例化(原型中包含其他内容),您可以执行以下操作:
function HumanObj(){
this.mouth = {
shout: function(word){
alert(word);
}
};
}
function HumanObj(){
function mouthObj() {
this.shout = function(word){
alert(word);
}
}
this.mouth = new mouthObj();
}
TopWay工作得很好。对不起,我没有足够的代表投票支持你,但谢谢你的帮助。@web_la-这从来都不是问题。高尔德:这很有帮助。:-)@你不能投票,但你可以点击小记号接受答案。这比一次投票更有价值。Top方法非常有效。对不起,我没有足够的代表投票支持你,但谢谢你的帮助。@web_la-这从来都不是问题。高尔德:这很有帮助。:-)@你不能投票,但你可以点击小记号接受答案。这比投票更有价值。