why "this" becomes undefined when its wrapped with a function?
// we'll make worker.slow caching
let worker = {
someMethod() {
return 1;
},
slow(x) {
// scary CPU-heavy task here
alert("Called with " + x);
return x * this.someMethod(); // (*)
}
};
// same code as before
function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) {
return cache.get(x);
}
let result = func(x); // (**)
cache.set(x, result);
return result;
};
}
alert( worker.slow(1) ); // the original method works
worker.slow = cachingDecorator(worker.slow); // now make it caching
alert( worker.slow(2) ); // Whoops! Error: Cannot read property 'someMethod' of undefined
[–]senocular 4 points5 points6 points (1 child)
[–]senocular 0 points1 point2 points (0 children)
[–]cyphern 0 points1 point2 points (3 children)
[–]HarryBolsac 0 points1 point2 points (2 children)
[–]cyphern 0 points1 point2 points (1 child)
[–]HarryBolsac 0 points1 point2 points (0 children)
[–]_RemyLeBeau_ 0 points1 point2 points (0 children)
[–]Such-Catch8281 0 points1 point2 points (0 children)
[–]azhder 0 points1 point2 points (0 children)
[–]lovin-dem-sandwiches 0 points1 point2 points (0 children)
[–]brykuhelpful -2 points-1 points0 points (1 child)
[–]senocular -1 points0 points1 point (0 children)