Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  178] [ 7]  / answers: 1 / hits: 38791  / 8 Years ago, tue, april 19, 2016, 12:00:00

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)
})

More From » class

 Answers
5

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.


[#62482] Monday, April 18, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maryann

Total Points: 600
Total Questions: 104
Total Answers: 97

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
maryann questions
Fri, Oct 15, 21, 00:00, 3 Years ago
Thu, Aug 13, 20, 00:00, 4 Years ago
Wed, Jul 17, 19, 00:00, 5 Years ago
Mon, Dec 17, 18, 00:00, 6 Years ago
;