Javascript 不能将类作为函数调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36724290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot call a class as a function
提问by ThomasReggi
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.
有什么方法可以让我将类作为函数调用。我正在寻找下面的功能,其中类中有一个main
方法,这就是我想要执行该方法的方法。
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)
})
回答by DerryckDX
Use the new
keyword when using classes in JavaScript. I had a similar problem until I added new
before the class name.
使用new
JavaScript中使用类时关键字。在我new
在类名之前添加之前,我遇到了类似的问题。
回答by Joe Velez
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()
然后我不需要使用new
,我可以简单地做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:
例如,我用香草JS写了一个简单的jQuery更换,我从字面上简单地通过改变取代〜90 +%的jQuery我的语法$
来J
如:
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.
附带说明一下,我发现使用 webpack 全局公开它更具挑战性......但我对 webpack 有点陌生(样板之外) - 所以是的。
Hope this helps someone.
希望这可以帮助某人。