Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
})
like image 548
ThomasReggi Avatar asked Apr 19 '16 16:04

ThomasReggi


People also ask

Can call a class as a function?

Likewise, if something looks like a function and quacks (calls) like a function, we can call it a function… even if it's actually implemented using a class or a callable object! Callables accept arguments and return something useful to the caller.

How do you call a function from another class in react JS?

To call a method from another class component in React. js, we can pass the class method as a prop to a child component. We have components Class1 and Class2 . And Class1 is a child of Class2 .

Why can't we declare a class with the class keyword in react?

Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute.

Which of the following is correct about prop in react?

Which of the following is correct about prop in react? Explanation: Props cannot be changed, they are immutable. A prop is a special keyword, that stands for properties.


1 Answers

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

like image 50
EnigmaTech Avatar answered Oct 02 '22 10:10

EnigmaTech