Greg Daynes

Full Stack Software Design, Development & Management

Callable Class Instance

I encountered a situation in Javascript, where I needed a Class instance that could be called like a function.

StackOverflow to the rescue1

import test from 'node:test'
import assert from 'node:assert/strict'

test('Callable ClassInstance', () => {
  class Callable extends Function {
    constructor () {
      super('...args', 'return this.fn(...args)')
      return this.bind(this)
    }

    fn () {
      console.log('called')
    }
  }

  const callableInstance = new Callable()
  callableInstance()
})

Another approach, much simpler is to define a function, then attach properties to it.

test('Callable Object Instance', () => {
  function Callable() {

    const fn = function () {
      console.log('called')
    }

    fn.someProperty = 'prop'

    return fn
  }

  const callableInstance = Callable() 
  callableInstance()
})

This approach breaks sharing Prototype Shapes, so too many of these will be problematic for memory23.

References