Assume I have HOF:
const logStartEnd = fn => (...args) => {
console.log("Start")
fn(...args);
console.log("End")
}
And this class
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
area() {
return this.height * this.width;
}
}
I want to be able to use my HOF like this:
const r = new Rectangle(12, 2);
const f = logStartEnd(r.area);
f();
This errors out Cannot read property 'height' of undefined
because r.area
is unbound.
To fix it, I have to pass the function like this
const f = logStartEnd(r.area.bind(r))
f() // 24
Is there a way I can avoid the .bind()
?
Or perhaps a way to get a reference to the original object, in which case, I can just call fn.call(originalObject, ...args)