1

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())
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Jack
  • 58
  • 1
  • 9
  • Could you share the code that you're having trouble with? Also, an [MVCE](https://stackoverflow.com/help/mcve) would help. – maazadeeb Aug 17 '17 at 03:07
  • You [cannot use an arrow function as a method](https://stackoverflow.com/q/34361379/1048572), and `originFunc()` will not call the original value *as a method*. Read [how the `this` keyword works](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this). – Bergi Aug 17 '17 at 20:14

1 Answers1

0
// Decorator function Example

const bioObject = { name: 'Ashil jayaraj'};
// To add new property on the bio object called 'Age': 26

const decoratorFn = (age) => {
  // Its a function returning new function
  return (bio) => {
    bio['age'] = age;
  }
  // This returned function just assign a key value pair on the object.
};

decoratorFn(26)(bioObject);
// onthe above line we are passing to function parameters
// 26 will be considered as Line no 12: age
// bioObject considered as Line no 14: obj (Argument)

console.log('bio object ', bioObject);
AJ Ashil
  • 1
  • 1