[英]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);
}
Hi, I give up for this. 嗨,我为此放弃。 Any one help me or have another way to call the function? 有人可以帮助我或有其他方式调用该函数吗?
Try this: 尝试这个:
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);
}
Hope this help. 希望能有所帮助。
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/ JSFiddle: http : //jsfiddle.net/DRfzc/
There is no way to call secondFunction()
from outside firstFunction()
without modifying firstFunction()
. 有没有办法来调用secondFunction()
从外面firstFunction()
而无需修改firstFunction()
If that is acceptable keep reading... 如果可以接受,请继续阅读...
Method 1: Modify firstFunction()
to return a reference to secondFunction()
: 方法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);
}
Method 2: Have firstFunction()
put a reference to secondFunction()
in a variable accessible outside its scope: 方法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);
}
Note that with either method you have to actually call firstFunction()
before trying to use the inner function. 请注意,无论使用哪种方法,您都必须在尝试使用内部函数之前实际调用 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.