2013-10-29 31 views
0

爲什麼這根本不起作用?「回調不是函數」和function.apply()

它說typeof(callback)= undefined。

function A(a,callback) 
{ 
document.write(typeof(callback)); 
callback(); 
return a; 
} 

function Run(func,args) 
{ 

    return func.apply(this||window, args || [ 
    function() { document.write("blah")} 
    ]); 

} 


Run(A,[1]); 

然而,不使用function.apply它正常工作:

function Run2(func,arg) 
{ 

    return func(arg, 
    function() { document.write("blah")} 
); 

} 

Run2(A,1); 

請耐心等待我是新來的JS。

回答

0

apply第一個參數是範圍,而第二個參數數組。看起來你有這個,但argsRun(A,[1]);是隻有一個參數(1)這將與a參數對齊,但你失蹤該函數。另一方面,如果沒有設置args,則選擇使用單個參數[ function()... ]創建一個數組,該數組將再次與a對齊。

從它的外觀來看,你試圖合併/連接兩個數組,實際上||被用作比較運算符,或者更確切地說是or賦值。

試試這個:

func.apply(this||window,args.concat([function() { document.write("blah")}])); 

args.push(function() { document.write("blah")}); 
func.apply(this||window,args); 
0

該問題實際上發生在A函數中,callback變量。如果你寫的A功能如下您將不會收到此錯誤:

function A(a, callback) { 
    var type = typeof callback; 
    document.write(type); 
    if(type == "function") callback();//ensure callback is a function 
    return a; 
} 
0

apply()會將第一個參數,並在函數調用使用它作爲this,並使用第二個參數作爲參數傳遞給該呼叫。所以RUN2被調用像這樣(其中<func>是你的匿名函數):

A(1, <func>); 

運行只傳遞一個參數在參數數組,1並調用它像這樣:

A(1) 

什麼你要做的是用這個替換您的運行(我認爲):

function Run(func,args) 
{ 
    args.push(function() { document.write("blah")}); 
    // args is now [1, function(){...}] 
    return func.apply(this||window, args); 
} 
0

您需要的2數組長度爲您Run()函數T o使用A()工作,因爲它需要兩個參數。你只有1個參數,如[1]。您需要[1, func],因此以下將是您的解決方案:

// the keyword this always exists 
function Run(func, args){ 
    args.push(func); 
    return func.apply(this, args || [function(){document.write("blah")}]); 
}