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 badges4 Answers
Reset to default 6The 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
评论列表(0条)