[英]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.