最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Instantiate JavaScript object and call method at once - Stack Overflow

programmeradmin4浏览0评论

I want to instantiate a simple JavaScript object, and call its method immediately. Is is possible to do it simply, like in PHP:

(new Class('attr', 'attr2'))->myMethod();

Is there a similar syntax in JavaScript?

I want to instantiate a simple JavaScript object, and call its method immediately. Is is possible to do it simply, like in PHP:

(new Class('attr', 'attr2'))->myMethod();

Is there a similar syntax in JavaScript?

Share Improve this question asked Aug 9, 2015 at 11:39 Isty001Isty001 1441 silver badge11 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

The same way, but with the dot notation (standard javascript):

(new MyObject(1)).toString()

You should just have tried it in the console because the answer is simply yes:

(new Foo()).bar();

but javascript is even better because you don't even need the braces:

new Foo().bar();

Simply,

 (new ClassName()).methodName();

you can even chain the methods If you return this from methodName()

(new ClassName()).methodName().secondMethod();

var date = new Date();
alert('With later invocation '+date.toDateString())

alert('With immediate invocation '+(new Date()).toDateString())

You can but you have to assign the instance of that new object to a variable. You can't just call (new MyObject(1)).myMethod().

From my demo:

(new myMethod('bob','tony')).log();

will produce an error:

undefined undefined _display:28:3

TypeError: (intermediate value)(...) is undefined

But this will produce the right result:

var a = (new myMethod('bob','tony')).log(); // bob tony

DEMO

发布评论

评论列表(0)

  1. 暂无评论