繁体   English   中英

在函数外如何调用此函数?

[英]How to call this function outside the function?

function firstFunction()
{
  stringWord = "Hello World";
  function secondFunction()//How to call this function in thirdfunction() ??
  {
    alert(stringWord);
  }
} 

function thirdFunction()
{
  run = setTimeout( ... , 5000);
}

嗨,我为此放弃。 有人可以帮助我或有其他方式调用该函数吗?

尝试这个:

 function firstFunction()
        {
          stringWord = "Hello World";
          this.secondFunction = function()//How to call this function in thirdfunction() ??
          {
            alert(stringWord);
          }
        }
        var instand = new firstFunction();
        function thirdFunction(){
            run = setTimeout( 'instand.secondFunction()', 5000);
        }

希望能有所帮助。

function firstFunction()
{
  stringWord = "Hello World";
  return function secondFunction()//How to call this function in thirdfunction() ??
  {
    alert(stringWord);
  };
}

secondFunction = firstFunction(); 

function thirdFunction()
{
  run = setTimeout( 'secondFunction()' , 5000);
}

JSFiddle: http : //jsfiddle.net/DRfzc/

有没有办法来调用secondFunction()从外面firstFunction()而无需修改firstFunction() 如果可以接受,请继续阅读...

方法1:修改firstFunction()以返回对secondFunction()的引用:

function firstFunction() {
  stringWord = "Hello World";
  return function secondFunction() {
    alert(stringWord);
  }
}
// And then call `firstFunction()` in order to use the function it returns:
function thirdFunction() {
  run = setTimeout(firstFunction(), 5000);
}
// OR
var secondFunc = firstFunction();
function thirdFunction() {
  run = setTimeout(secondFunc, 5000);
}   

方法2:拥有firstFunction()付诸参考secondFunction()在其范围以外的变量访问:

var secondFunc;
function firstFunction() {
  stringWord = "Hello World";
  function secondFunction() {
    alert(stringWord);
  }
  window.secondFunc = secondFunction;  // to make a global reference, AND/OR
  secondFunc = secondFunc; // to update a variable declared in same scope
                           // as firstFunction()
}
firstFunction();
function thirdFunction() {
  run = setTimeout(secondFunc, 5000);
}

请注意,无论使用哪种方法,您都必须在尝试使用内部函数之前实际调用 firstFunction()

var stringWord;
function firstFunction()
{
  stringWord = "Hello World";
  secondFunction();
} 

 function secondFunction()
  {
    alert(stringWord);
  }

function thirdFunction()
{
  run = setTimeout( 'secondFunction()' , 5000);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM