miir miir - 1 year ago 146
Javascript Question

How to construct Date object instance and invoke its function on the same line?

I would like to construct a

object and invoke the
function in the same line. However, chrome is giving me an error.

> new Date().getTimeZoneOffset();

x Uncaught TypeError: (intermediate value).getTimeZoneOffset is not a function(…)

I created a random test object, and was able to instantiate the test object and call its function in the same line.

Why am I unable to do this with the Date object?

Answer Source

The function is getTimezoneOffset, not getTimeZoneOffset. So, it just works:

new Date().getTimezoneOffset()

Of course, not needed in this case, but in cases when you want something to run first then use its return to call another function, you could use an Immediately-Invoked Function Expression (IIFE), like this:

(function () { return new Date() })().getTimezoneOffset()

And with ES6 arrow functions:

(() => new Date())().getTimezoneOffset()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download