[英]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 . 在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. new Date()
和(new Date())
都是计算为Date对象的表达式,您可以在上面自由调用方法。
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. 在没有中间分配的情况下实例化对象并调用其方法的模式是A-OK,在那里没有问题。
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 :)
更不用说它更便宜的事实了:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.