Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 930
HerbalMart Avatar asked Feb 22 '23 17:02

HerbalMart


1 Answers

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
like image 103
Manse Avatar answered May 01 '23 16:05

Manse