Isty001
Isty001

Reputation: 144

Instantiate JavaScript object and call method at once

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?

Upvotes: 5

Views: 2189

Answers (4)

slebetman
slebetman

Reputation: 113964

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();

Upvotes: 1

Andy
Andy

Reputation: 63550

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

Upvotes: 0

vinayakj
vinayakj

Reputation: 5681

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

Upvotes: 0

Amit
Amit

Reputation: 46341

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

(new MyObject(1)).toString()

Upvotes: 6

Related Questions