简体   繁体   中英

Just seen a factory style object creating in JavaScript (without literals). What else do I need to know?

I have just seen this in code

var thisYear = (new Date()).getFullYear();

See it live on JSbin .

This is cool, as I've always done something like that in 2 lines, ie create the new object instance and assigned it to a variable, then called the method on it.

Is this new method fine to use everywhere? Any gotchas?

That's not new, but yes it's safe. You don't actually need the parentheses either:

new Date().getFullYear();

new Date() and (new Date()) are both expressions that evaluate to a Date object, which you can freely call methods on.

You can even call methods directly on numbers:

(1000).toExponential()

In this case you do need the parens.

The pattern of instantiating an object and calling its methods without intermediate assignment is A-OK, no problem there.

With dates, though, one must be careful not to do the following:

var hours = new Date().getHours();
var minutes = new Date().getMinutes(); //Say at, 15:30:59
var seconds= new Date().getSeconds();  //Some ticks passed, now it's 15:31:00

var time = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" +  (seconds < 10 ? "0" + seconds : seconds);
alert(time); //Oops, it's 15:30:00!

The example is contrived, but it's good to keep in mind if you're using a context-aware object, sometimes you want a single instance to do multiple operations. Not to mention the fact that it's cheaper :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM