简体   繁体   中英

Javascript exercism solution. Why is one better than the other?

I solved the Gigasecond exercism in Javascript with this solution. 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? Also is there a difference between using Number and getTime()?

WoW! in the first code :

  1. beginAtStartOfDay is created in the global scope.
  2. gigasecondConverter is created in the global scope.
  3. then you return beginAtStartOfDay in gigasecondConverter

okey now let me explain a bit what appened to your poor memory :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.

but the biggest memory waste is EACH time you gonna call gigasecondConverter you will create a NEW instance of beginAtStartOfDay . Imagine just using gigasecondConverter 100 times and 99 times you do memory waste ! poor memory :D

in the second :

  1. Gigasecond is created in the global scope.
  2. date is created in the prototype of Gigasecond .
  3. _beginningOfTheDay is created in the prototype of Gigasecond .

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 .

Prototype in JavaScript is very powerfull! using it for a function you gonna call and return many times is always a good thing for your memory. :)

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