gpt4 book ai didi

javascript - javascript中的多个嵌套函数

转载 作者:行者123 更新时间:2023-11-29 18:22:43 31 4
gpt4 key购买 nike

我正在对一个 javascript 项目进行反向工程,需要将一个函数注入(inject)到一些已经编写好的代码中。

我希望能够在 javascript 中调用如下函数:

human.mouth.shout(word);

所以这将调用使对象“大喊”的函数。

我的问题是,我如何创建人类对象的子属性。据我所知,我只能在 javascript 中有一个嵌套函数,所以最基本的我有这样的东西:

function HumanObj(){
this.shout = function(word){
alert(word);
}
}

然后调用它,我会使用:

var human = new HumanObj;
human.shout("HELLO WORLD");

所以这会给我们警报:“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);
}
};
}

或者,如果您需要 mouth 可以实例化(在其原型(prototype)中添加其他内容),您可以:

function HumanObj(){
function mouthObj() {
this.shout = function(word){
alert(word);
}
}
this.mouth = new mouthObj();
}

关于javascript - javascript中的多个嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840748/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com