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

Can somebody please explain why the below code returns undefined 2 times ?var test = function (theArr)

Can somebody please explain why the 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

Can somebody please explain why the 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
Share edited Oct 15, 2013 at 12:38 Stephane Rolland 40k38 gold badges126 silver badges172 bronze badges asked Oct 13, 2011 at 10:43 HerbalMartHerbalMart 1,7393 gold badges27 silver badges50 bronze badges 2
  • Why do you need to use the call method? – Jamie Dixon Commented Oct 13, 2011 at 10:46
  • You mean that it shows "Undefined" in the alert dialog, right? Because there are not return values anywhere. – Till Helge Commented Oct 13, 2011 at 10:46
Add a ment  | 

1 Answer 1

Reset to default 8

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744924632a4601355.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信