2011-10-13 53 views
3

有人可以請解釋爲什麼下面的代碼返回2次未定義?通過調用和調用調用Javascript函數不能處理參數

var test = function (theArr) { 
     alert(theArr); 
    }; 

    test.call(6);    //Undefined 

    var theArgs = new Array(); 
    theArgs[0] = 6; 

    test.apply(theArgs)   //Undefined 
+0

爲什麼你需要使用呼叫的方法? –

+0

您的意思是它在警告對話框中顯示「Undefined」,對不對?因爲任何地方都沒有返回值。 –

回答

5

爲JavaScript調用方法的語法:

fun.call(object, arg1, arg2, ...)

爲JavaScript的語法應用方法:

fun.apply(object, [argsArray])

的主要差別是該呼叫()接受一個參數列表,而apply()接受一個單獨的參數數組。

所以,如果你要調用它打印東西的功能,並通過一個對象的範圍爲它的執行,你可以這樣做:

function printSomething() { 
    console.log(this); 
} 

printSomething.apply(new SomeObject(),[]); // empty arguments array 
// OR 
printSomething.call(new SomeObject()); // no arguments 
+1

所以要明確解決給定的代碼:'test.call(this,6);'或'test.apply(this,theArgs);' –

+0

謝謝!我現在正在從Jquery切換回Javascript的基礎知識,並且它也需要一些使用:) – HerbalMart

+0

爲了進一步闡明:Object參數指定執行該函數時將涉及的this關鍵字。 –