Reputation: 185
I have a problem passing an array.push function in javascript having a code like this:
const array = [];
addToArray("works", (e) => array.push(e));
addToArray("notWorks", array.push);
doConsoleLog("hello", console.log);
function addToArray(element, pushFn) {
pushFn(element);
}
function doConsoleLog(message, log) {
log(message);
}
Just curious how's that first call of addToArray works, but second causes TypeError: Cannot convert undefined or null to object
. How is it possible? Type of array.push is a function. It is not possible to pass functions directly like in the case of console.log above, which works pretty well?
Upvotes: 3
Views: 2875
Reputation: 69296
push
is a method of array
. When invoked, it uses this
as a reference to the object it is being called on. If you pass it around like a normal function, you will lose that reference, the method will use the value of this
defined at the moment of the call (inside addToArray
, this
is probably document.window
), and will therefore fail.
In order to pass around a method, you need to bind it to the object you want it to operate on, in this case array
. This is true for any object method in JavaScript. Function.prototype.bind()
exists exactly for this purpose: it "binds" a function (in this case your method) to a given value of this
, in order to work correctly.
const array = [];
addToArray("now it works", array.push.bind(array));
// or
addToArray("now it works", Array.prototype.push.bind(array));
function addToArray(element, pushFn) {
pushFn(element);
}
Upvotes: 4
Reputation: 22
Your code have a lot of mistakes. What exactly should do this code? if you want to push new items in array use spread operator
const array = [...[], "works", "notWorks"]
const array = [];
addToArray("works", (e) => array.push(e));
addToArray("notWorks", array.push);
doConsoleLog("hello", console.log);
function addToArray(element, pushFn) {
pushFn(element); //function must return something
}
function doConsoleLog(message, log) {
log(message); //function must return something
}
Upvotes: -2
Reputation: 87
Once you pass a function like you did in the second case, it executes itself immediately, and array.push doesn't really mean something.
A callback function should be executed later on in the outer function.
Unlike the second example, in the first one you don't execute the function immediately, but only when you call it inside the outer function.
Upvotes: -1