Created
September 28, 2020 23:56
-
-
Save rekhubs/1802e45ef553dbf0a0230d75d87a6e06 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<script> | |
// source from https://javascript.info/call-apply-decorators | |
'use strict'; | |
let name = "global-name"; | |
console.log('LINE 6 this.name:', this.name); | |
let worker = { | |
name: "worker-name", | |
someMethod() { | |
return 1; | |
}, | |
slow(x) { | |
console.log("line 15 Called with " + x); | |
//alert("Called with " + x); | |
console.log('LINE 16 this.name:', this.name); | |
return x * this.someMethod(); // (*) | |
} | |
}; | |
function cachingDecorator(func) { | |
console.log('what is the passed in "func":', func, '\nwhat is this:', this); | |
let name = "cachingDeco-name"; | |
//console.log('LINE 25 this.name:', this.name); | |
let cache = new Map(); | |
return function(x) { | |
if (cache.has(x)) { | |
return cache.get(x); | |
} | |
console.log('what is this now:', this); | |
console.log('LINE 32 this.name:', this.name); | |
let result = func.call(this, x); // "this" is passed correctly now | |
cache.set(x, result); | |
return result; | |
}; | |
} | |
worker.slow = cachingDecorator(worker.slow); // now make it caching | |
//console.log('after all, worker.slow() becomes:', worker.slow); | |
console.log('line 43:', worker.slow(2) ); // works | |
console.log('line 44:', worker.slow(5) ); // works | |
//alert( worker.slow(2) ); // works | |
//alert( worker.slow(2) ); // works, doesn't call the original (cached) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment