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, i.e. 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 :)
精彩评论