需要帮助调用 text_a(),它最初在 foo() 中声明,在被调用的函数 foo() 内

问题描述

我正在创建与此类似的代码

function foo(type,callback) {
 if(type === "a") {
  function text_a() {
   return "a";
  }
 }else if(type === "b") {
  function text_b() {
   return "b";
  }
 }else if(type === "c") {
  function text_c() {
   return "c";
  }
 }
 if(typeof callback === "function") callback();
}

foo("a",function() {
 console.log(text_a());
});

我希望 text_a() 中的函数 foo() 仅在类型等于相关类型并在 foo() 函数内部调用时才可用。但是,这不起作用。我不断收到一条错误消息,指出 text_a() 未定义,这是没有意义的,因为在调用 foo 函数时,如果类型为“a”,它还应该声明 text_a 函数.

解决方法

只需保存对函数的引用并将其传递给回调即可..

例如

function foo(type,callback) {
 var fn;
 if(type === "a") {
  fn = function text_a() {
   return "a";
  }
 }else if(type === "b") {
  fn = function text_b() {
   return "b";
  }
 }else if(type === "c") {
  fn = function text_c() {
   return "c";
  }
 }
 if(typeof callback === "function") callback(fn);
}

foo("a",function(fn) {
 console.log(fn());
});

foo("b",function(fn) {
 console.log(fn());
});