簡體   English   中英

Javascript運動解決方案。 為什么一個比另一個更好?

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

我通過這種解決方案解決了Java腳本中的千兆秒執行問題。 我想知道我可以做得更好:

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;

})();

為什么自執行功能和原型使用比直接在函數上定義date方法更好? 使用Number和getTime()之間也有區別嗎?

哇! 在第一個代碼中

  1. 在全局范圍內創建beginAtStartOfDay
  2. gigasecondConverter在全局范圍內創建。
  3. 然后在gigasecondConverter中返回beginAtStartOfDay

好的,現在讓我解釋一下您記憶力不佳的原因:D。 beginAtStartOfDay被存儲在全局范圍內,然后在gigasecondConverter中使用它,因此他在gigasecondConverter范圍內創建了另一個beginAtStartOfDay ,這浪費了內存。

最大內存浪費 一次你會打電話給gigasecondConverter您將創建beginAtStartOfDay實例。 想象一下,僅使用gigasecondConverter 100次和99次就會浪費內存! 記憶力差:D

第二個

  1. 千兆秒創建於全局范圍內。
  2. 日期是在Gigasecond原型創建的
  3. _beginningOfTheDay是在Gigasecond原型創建的

現在, 每當你會打電話給Gigasecond即使你撥打100倍這只會造成_beginningOfTheDay一個實例,它總是會調用Gigasecond相同的原型功能。

JavaScript中的原型非常強大! 將其用於將要調用並返回多次的函數對您的記憶總是一件好事。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM