I call a method on an object. And the method takes a callback function as a parameter. As:
obj.method(callbackFn);
Inside the callback function, I want to work with the object the method is called upon. I want to declare the callback function and save it to a global variable since I may use this callback later in multiple methods upon multiple objects. As:
const predeclaredFunc = () => {
//func body needs to work with the obj that calls the method which has this predeclared func as callback argument
};
const obj1 = {
methodA(callbackFn){callbackFn()};
};
const obj2 = {
methodB(callbackFn){callbackFn()};
};
obj1.methodA(predeclaredFunc); // predeclaredFunc will work with obj1
obj2.methodB(predeclaredFunc); // predeclaredFunc will work with obj2
So I have to use something like the this
keyword to refer to the object in the callback function body, instead of using its name. But I dont know how to.
For example, with the array.forEach method, say I want the callback to console log the array for each element of the array.
I will want to have something like this (not working):
const arr = [0, 1, 2]; //any random array with length 3
/ I want the callback to console log the array 3 times
const callback = () => {
console.log(this);
}
//does using arrow function in this case make difference from using func declaration/expression?
arr.forEach(callback);
//not working. it's logging ' {} {} {} ' to the console
Help Please! Many thanks!