通过调用和apply调用的Javascript函数无法处理参数

Her*_*art 3 javascript parameters function call undefined

有人可以解释为什么下面的代码返回undefined 2次?

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

    test.call(6);               //Undefined

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

    test.apply(theArgs)         //Undefined
Run Code Online (Sandbox Code Playgroud)

Man*_*eUK 7

JavaScript调用方法的语法:

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

JavaScript apply方法的语法:

fun.apply(object, [argsArray])

主要区别在于call()接受参数列表,而apply()接受单个参数数组.

因此,如果您想调用一个打印内容并传递对象作用域的函数来执行,您可以执行以下操作:

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

printSomething.apply(new SomeObject(),[]); // empty arguments array
// OR
printSomething.call(new SomeObject()); // no arguments
Run Code Online (Sandbox Code Playgroud)