Learning reactive programming and encouter this bit of code,
JavaScript
x
2
1
results.push.apply(results, subArray);
2
understand apply
FULL CODE
JavaScript
1
9
1
Array.prototype.concatAll = function() {
2
var results = [];
3
this.forEach(function(subArray) {
4
results.push.apply(results, subArray);
5
});
6
7
return results;
8
};
9
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:
JavaScript
1
13
13
1
var o1 = {
2
name: 'First object',
3
f: function(a, b ,c) {
4
console.log(this, a, b, c);
5
}
6
};
7
o1.f('Hello', 'World', '!');
8
var o2 = {
9
name: 'Second object'
10
};
11
var some_function = o1.f; // This illustrates that the function is not bound to o1...
12
some_function.apply(o2, ['foo', 'bar', 'baz']);
13