ThomasReggi
ThomasReggi

Reputation: 59365

Cannot call a class as a function

Is there any way that would allow me to call a class as a function. I'm looking to have the functionality below, where there's a main method within the class and that's the one I want to have the method execute.

class test {
  constructor () {
    return this.main
  }
  main () {
    return Promise.resolve('thomas')
  }
}

test().then(name => {
  console.log(name)
})

It seems my only other option would be to have a wrapper function like this.

class Test {
  constructor (name) {
    this.name = name
  }
  main () {
    return Promise.resolve(this.name)
  }
}

let test = (name) => {
  return new Test(name).main()
}

test('thomas').then(name => {
  console.log(name)
})

Upvotes: 16

Views: 40760

Answers (2)

Joe Velez
Joe Velez

Reputation: 140

I know I'm years late, but the solution I found was this:

// MyLib.js
class MyLib {
  constructor(selector){}
  someMethod(){}
  ...
}

export function MyFunction(selector){
  return new MyLib(selector)
}

Then I don't need to use new, I can simply do MyFunction().someMethod()

For example, I wrote a simple jQuery replacement using vanilla js and I literally replaced ~90+% of my jQuery syntax simply by changing $ to J such as:

J().ready(function(){})
J().ajax(...).then((res)=>{}).catch((err)=>{}) // used axios here
J('.someClass').find('li').last()
J('header').css({display:'block'})
//etc

On a side note, I found it a little more challenging to globally expose it with webpack... but I'm a little new to webpack (outside of boilerplates) - so yea.

Hope this helps someone.

Upvotes: 2

EnigmaTech
EnigmaTech

Reputation: 338

Use the new keyword when using classes in JavaScript. I had a similar problem until I added new before the class name.

Upvotes: 24

Related Questions