1

For example

const obj = {
  get test() {
    return 'something'
  }
}

Is there a way to return obj.test as the function itself as opposed to 'something', as there is currently a use case where I don't want the function to execute immediately. Or is the only method to make it not a getter function

Phil
  • 157,677
  • 23
  • 242
  • 245
A. L
  • 11,695
  • 23
  • 85
  • 163
  • 1
    You could always create a normal method and getter, eg `const ob = { getTest() { return "something" }, get test() { return this.getTest() } }` – Phil Mar 18 '21 at 00:39
  • 1
    Use an anonymous function: `function() { return obj.test; }` when you don't want it to execute immediately. – Barmar Mar 18 '21 at 00:43
  • 1
    If you want deferred execution, you could just wrap it: `() => obj.test` and use that in any context where you need a function that evaluates later. – tadman Mar 18 '21 at 00:43

1 Answers1

0

You can store the function in a separated variable and define the getter with the __defineGetter__ method:

const obj = {}

var obj_getter = function(){
    return 'something'
};

obj.__defineGetter__('test', obj_getter);

console.log(typeof obj_getter);
console.log(obj.test);

And the result is

"function"
"something"
Filipizaum
  • 81
  • 7