JS decorator apply on class function can only get class as target. like this:
Common {} 'retrieveMultiple' { value: [AsyncFunction: retrieveMultiple],
writable: true,
enumerable: false,
configurable: true }
But this operation will make function unusable if this function used it's instance variable.
Decorator at this situation cannot get instance. Have any method to solve this ?
Below code is a example used to recurrent this situation, run with babel and babel-plugin-transform-decorators-legacy please.
function decr (target, property, descriptor) {
// you can check that target is class
console.log(target, property, descriptor)
const originFunc = descriptor.value
descriptor.value = () => {
let result = originFunc()
return result + 1
}
return descriptor
}
class Example {
constructor (value) {
this.value = value
}
@decr // comment this line to check different
showNum () {
return this.value // access instance variable
}
}
const test = new Example(3)
console.log(test.showNum())