nim_cch
nim_cch

Reputation: 15

Why Array.push apply and call not work?

I am don't understand why this code not work. Here a.push.apply(this, b); and a.push.call(window, 7); no works too.

<script>
        var a = [1, 2, 3, 4];
        var b = [7];

        a["push"].apply(this, b);
</script>

Upvotes: 1

Views: 938

Answers (1)

mziccard
mziccard

Reputation: 2178

You are "applying" push to the wrong object. Try:

<script>
        var a = [1, 2, 3, 4];
        var b = [7];

        a["push"].apply(a, b);
</script>

Same reasoning for a.push.call(a, 7);.

a["push"] only gives you a function back with no information on the invocation object. When you call apply you are applying the function, what you need to do is to provide an "object context", that is the object on which you want to apply the function, and the function parameters.

Upvotes: 6

Related Questions