Hello-World
Hello-World

Reputation: 9545

javascript apply not firing each index in array passed into it

Why does objA.myf3.apply(this,a); only console.log the first index in the array a

how am I using apply wrong i'm expecting myf3:function(myarr) to be called for each index in the array

and am expecting it to log 1 2 3 4 ......

Thanks for the help.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">

        var objA = {

            myf3:function(myarr){

                console.log(myarr); // why does only the first index of the array come through?

            }
        };


        var objB = {

            myfb2:function(){

                var a = [1,2,3,4,5,6,7,8,9];

                objA.myf3.apply(this,a);

            }
        };

        objB.myfb2();

    </script>
</head>

<body>

test apply?????

</body>

Upvotes: 1

Views: 45

Answers (1)

thefourtheye
thefourtheye

Reputation: 239453

Function.prototype.apply will break the array parameter and passes the individual values as parameters. So, in this case, you would have got 9 parameters. You can confirm this by do this

myf3:function(myarr) {
        console.log(arguments); // arguments will print all the parameters passed
     }

So, you should use Function.prototype.call here

objA.myf3.call(this, a);

it will pass the parameters as they are.

var objA = {
    myf3: function(myarr) {
        console.log(arguments);
    }
};
var objB = {
    myfb2: function() {
        var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        objA.myf3.apply(this, a);
    }
};
objB.myfb2();
# { '0': 1,
#   '1': 2,
#   '2': 3,
#   '3': 4,
#   '4': 5,
#   '5': 6,
#   '6': 7,
#   '7': 8,
#   '8': 9 }

But when we use .call,

var objA = {
    myf3: function(myarr) {
        console.log(myarr);
    }
};
var objB = {
    myfb2: function() {
        var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        objA.myf3.call(this, a);
    }
};
objB.myfb2();
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Upvotes: 2

Related Questions