gpt4 book ai didi

javascript - 将 javascript 中的函数作为全局函数调用

转载 作者:行者123 更新时间:2023-11-28 16:20:24 24 4
gpt4 key购买 nike

我在 javascript 中有一个主函数,即 function a() { some code here },并且在这个主函数中我还有一个子函数,如下所示

function a() {

function b() {

// some code here
}

}

现在我想直接调用函数b。那么如何做到这一点。

最佳答案

你不能。但是,您可以执行以下操作:

function a() {

this.b = function () {

some code here
}
}

然后这样调用它:

var x = new a();
a.b();

您还可以使用函数创建对象文字:

var a = {
b: function ()
{
//some code here
}
};

然后只需说:

a.b();

您还可以在函数对象本身上创建一个属性,并以这种方式访问​​它:

function a()
{
};

a.b = function ()
{
//Some code here
};

然后用以下方式调用它:

a.b();

关于javascript - 将 javascript 中的函数作为全局函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9867098/

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