Skip to content
Advertisement

array.push.apply to implment ‘concat’ with explain

Learning reactive programming and encouter this bit of code,

results.push.apply(results, subArray);

understand apply

FULL CODE

Array.prototype.concatAll = function() {
    var results = [];
    this.forEach(function(subArray) {
        results.push.apply(results, subArray);
    });

    return results;
};

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

but when this code appear and get my head spinning. it’s pretty much doing the concat. can someone please explain?

many thanks

Advertisement

Answer

some_function.apply(obj, [a, b, c])

is (basically…) the same as:

obj.some_function(a, b, c)

Which is: “invoke the function, referenced by ‘some_function’, with ‘obj’ as the ‘this argument’, and the list of parameters as parameters”.

That is, calling the function (in your case, ‘push’) as if it was a member of ‘obj’ (in you case ‘results’).

See: Function.prototype.apply for details.

An example to play around with:

var o1 = {
    name: 'First object',
    f: function(a, b ,c) {
           console.log(this, a, b, c);
       }
};
o1.f('Hello', 'World', '!');
var o2 = {
    name: 'Second object'
};
var some_function = o1.f; // This illustrates that the function is not bound to o1...
some_function.apply(o2, ['foo', 'bar', 'baz']);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement