[英]Javascript exercism solution. Why is one better than the other?
I solved the Gigasecond exercism in Javascript with this solution. 我通过这种解决方案解决了Java脚本中的千兆秒执行问题。 I would like to know what I could have done better:
我想知道我可以做得更好:
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
Why is this solution better? 为什么此解决方案更好?
(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;
})();
Why is the self-executing function and usage of prototypes better than just defining the date method directly on the function? 为什么自执行功能和原型使用比直接在函数上定义date方法更好? Also is there a difference between using Number and getTime()?
使用Number和getTime()之间也有区别吗?
WoW! 哇! in the first code :
在第一个代码中 :
okey now let me explain a bit what appened to your poor memory :D. 好的,现在让我解释一下您记忆力不佳的原因:D。 beginAtStartOfDay is memorized in the global scope, then you use it in gigasecondConverter so he creates another beginAtStartOfDay in the gigasecondConverter scope, its memory waste.
beginAtStartOfDay被存储在全局范围内,然后在gigasecondConverter中使用它,因此他在gigasecondConverter范围内创建了另一个beginAtStartOfDay ,这浪费了内存。
but the biggest memory waste is EACH time you gonna call gigasecondConverter you will create a NEW instance of beginAtStartOfDay . 但最大的内存浪费 每一次你会打电话给gigasecondConverter您将创建beginAtStartOfDay的新实例。 Imagine just using gigasecondConverter 100 times and 99 times you do memory waste !
想象一下,仅使用gigasecondConverter 100次和99次就会浪费内存! poor memory :D
记忆力差:D
in the second : 在第二个 :
Now EACH time you gonna call Gigasecond it will Only create ONE instance of _beginningOfTheDay even if you call 100 times, it will always call the SAME prototype function of Gigasecond . 现在, 每当你会打电话给Gigasecond即使你拨打100倍这只会造成_beginningOfTheDay的一个实例,它总是会调用Gigasecond的相同的原型功能。
Prototype in JavaScript is very powerfull! JavaScript中的原型非常强大! using it for a function you gonna call and return many times is always a good thing for your memory.
将其用于将要调用并返回多次的函数对您的记忆总是一件好事。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.