开发者

Javascript function called by call and apply can't handle a parameter

Can somebody please explain why the开发者_如何学Go below code returns undefined 2 times ?

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

    test.call(6);               //Undefined

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

    test.apply(theArgs)         //Undefined


The syntax for the JavaScript call method:

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

The syntax for the JavaScript apply method:

fun.apply(object, [argsArray])

The main difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

So if you want to call a function which prints something and pass an object scope for it to execute in, you can do:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜