How do I force an object to run as a function

Viewed 88

I’ve been using node.js for some time now and I realized that require is a function, and an object, or so it seems. You can do the following:

require('someModule')
let a = require.cache //not undefined

I’ve been trying to do this myself but I can’t figure out how. These are the things I tried:

function a() {
console.log('a')
}
let a = {test: 1}
//throws cannot declare variable twice

And reversed it

let a = {test:1}
function a() {
console.log('a')
}
//still throws

I even tried adding a toFunction method to a class, making an instance of it, and trying to call on the instance, which I hoped would work like toString(), but it still said a is not a function.

How can I do this myself? It’s probably super simple but I couldn’t find it anywhere when researching.

1 Answers

Declare the function first. Functions are objects, so you can then assign to a property of it.

function a() {
  console.log('a')
}
a.test = 1;

a();
console.log(a.test);

If you want to use object literal syntax instead of assigning to properties individually, you can use Object.assign.

function a() {
  console.log('a')
}
Object.assign(
  a,
  {
    test: 1,
    // other properties
  }
);

a();
console.log(a.test);

Related