我用这个解决方案解决了 Javascript 中的千兆秒练习。我想知道我可以做得更好:
var gigasecondConverter = function(unformattedDate) {
this.date = function() {
return beginAtStartOfDay(Number(unformattedDate) + 1000000000000)
}
}
beginAtStartOfDay = function(number) {
date = new Date(number)
date.setSeconds(0);
date.setMinutes(0);
date.setHours(0);
return date;
}
module.exports = gigasecondConverter
为什么这个解决方案更好?
(function() {
'use strict';
function Gigasecond(birthDate) {
this.birthDate = birthDate;
this.interval = 1000000000000;
};
Gigasecond.prototype.date = function() {
var gigasecondCelebrationDate = new Date(this.birthDate.getTime() + this.interval);
return this._beginningOfTheDay(gigasecondCelebrationDate);
};
Gigasecond.prototype._beginningOfTheDay = function(date) {
date.setSeconds(0);
date.setMinutes(0);
date.setHours(0);
return date;
};
module.exports = Gigasecond;
})();
为什么自执行函数和原型(prototype)的使用比直接在函数上定义日期方法更好?使用 Number 和 getTime() 之间有区别吗?
最佳答案
哇!在第一个代码中:
- beginAtStartOfDay 在全局范围内创建。
- gigasecondConverter 在全局范围内创建。
- 然后你在gigasecondConverter中返回beginAtStartOfDay
好吧,现在让我解释一下你内存力差的原因:D。 beginAtStartOfDay 被存储在全局范围内,然后你在 gigasecondConverter 中使用它,所以他在 gigasecondConverter 中创建了另一个 beginAtStartOfDay范围,它的内存浪费。
但是最大的内存浪费是每次你打电话的时间 gigasecondConverter您将创建一个beginAtStartOfDay的NEW实例。想象一下,仅使用gigasecondConverter 100 次和 99 次就会浪费内存!内存力差:D
在第二个中:
- 千兆秒是在全局范围内创建的。
- 日期是在千兆秒的原型(prototype)中创建的。
- _beginningOfTheDay是在千兆秒的原型(prototype)中创建的。
现在每次每次调用Gigasecond时,它只会创建ONE个_beginningOfTheDay<实例/em>即使你调用100次,它总是会调用SAMEGigasecond的原型(prototype)函数。
JavaScript 中的原型(prototype)非常强大!将它用于要多次调用和返回的函数对于您的内存来说总是一件好事。 :)
关于JavaScript 练习解决方案。为什么一个比另一个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602442/