Instantiate JavaScript object and call method at once - Stack Overflow

I want to instantiate a simple JavaScript object, and call its method immediately. Is is possible to do

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744252049a4565215.html

相关推荐

  • Instantiate JavaScript object and call method at once - Stack Overflow

    I want to instantiate a simple JavaScript object, and call its method immediately. Is is possible to do

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信