I came across the following example in the JS manual, which is functioning correctly:
let worker = {
someMethod() {
return 1;
},
slow(x) {
alert("Called with " + x);
return x * this.someMethod(); // (*)
}
};
function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) {
return cache.get(x);
}
let result = func.call(this, x); // now 'this' is passed correctly
cache.set(x, result);
return result;
};
}
worker.slow = cachingDecorator(worker.slow); // now make it a caching function
alert( worker.slow(2) ); // works
alert( worker.slow(2) ); // works without calling the original function (caching activated)
My question is about how the reference to "this" gets passed into the cachingDecorator function, when cachingDecorator is not declared inside of the object and is called as
worker.slow = cachingDecorator(worker.slow)
? I am referring specifically to this line inside the cachingDecorator: let result = func.call(this, x)
.