gpt4 book ai didi

javascript - 在 IIFE 中引用一个函数

转载 作者:行者123 更新时间:2023-12-01 14:20:30 24 4
gpt4 key购买 nike

我有以下逻辑:

var first_function = (function(d3, second_function) {
function third_function(param1, param2) {
/* do stuff here */
}
})(d3, second_function);

在 IIFE 结构之外,要访问第三个函数,我通常可以这样做:

first_function.third_function(data1, data2);

我哪里错了?

最佳答案

如果你想从 IIFE 访问一个属性,你需要通过返回一个对象来使该属性可用

var first_function = (function(d3, second_function) {

// this function is unavailable to the outer scope
function third_function(param1, param2) {
/* do stuff here */
}

// this object allows us to access part of the inner scope
// by passing us a reference
return {
third_function: third_function
}
}})(d3, second_function);

有趣的是,我们还可以利用这一点来创建“私有(private)”方法和变量。

var first_function = (function(d3, second_function) {

// this function is unavailable to the outer scope
function third_function(param1, param2) {
/* do stuff here */
}

var myPrivate = 0; // outer scope cannot access

// this object allows us to access part of the inner scope
// by passing us a reference
return {
third_function: third_function,
getter: function() {
return myPrivate; // now it can, through the getter
}
}
}})(d3, second_function);

如果您想了解更多有关其工作原理的信息,我建议您阅读有关 JavaScript 作用域和闭包的内容。

关于javascript - 在 IIFE 中引用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33247167/

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