Javascript 引用生命中的函数
我有以下逻辑:Javascript 引用生命中的函数,javascript,function,logic,closures,iife,Javascript,Function,Logic,Closures,Iife,我有以下逻辑: 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); 我哪里出错了?它没有返回
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);
我哪里出错了?它没有返回它,所以函数只是在蒸发。您可以这样做:
var first_function = (function(d3, second_function) {
function third_function(param1, param2) {
/* do stuff here */
}
return third_function;
})(d3, second_function);
first_function( paramForThirdFunc1,paramForThirdFunc2);
然后,您可以这样访问它:
var first_function = (function(d3, second_function) {
function third_function(param1, param2) {
/* do stuff here */
}
return third_function;
})(d3, second_function);
first_function( paramForThirdFunc1,paramForThirdFunc2);
如果要从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);
有趣的是,我们还可以利用它来创建“私有”方法和变量
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作用域和闭包。注意IIFE不会返回任何东西,它会立即执行,所以基本上
第一个函数是未定义的?你的IIFE返回什么?您需要返回一个具有第三个函数作为属性的对象,否则您将无法访问它。此外,您不能访问IIFE之外的third\u函数
,这就是闭包所做的,内部函数在外部作用域中不可用,除非您返回使其可用的内容。真正的问题变成了;你为什么要用生命?欣赏这些见解,@adeneo。我主要是利用生活来更好地了解他们,也不污染全球。试试这个。我会尽快报告。@daveycroqet我犯了一个错误,请再次检查:)是的,这是他肯定想要的。我希望我能给你们两个答案。哈沙尔只是更快,尽管这是一个更加充实的答案,我感谢你们。