在被调用函数中只获取必要的构造函数 属性

Get only necessary constructor property within a called function

我对构造函数很陌生。

出于个人目的,我正在编写一个脚本来扩展 Date() 对象的可能性。

但是当我使用 new 创建对象并请求特定的 属性 时,所有属性都会被处理(正如我在控制台中实际看到的那样)。如何避免这种情况以节省一些资源?

例如,如果我这样做:var bisextile = new RightTime(2022).IsBisextile,我不想计算 RightTime().NextFullMoon

谢谢

const RightTime = function(a,m,j,h,min) {
  var getLunarAge = function(d,b,c) {
    d = void 0 === a ? new Date() : new Date(d,b,c);
    var b = d.getTime();
    d = d.getTimezoneOffset();
    b = (b / 86400000 - d / 1440 - 10962.6) / 29.530588853;
    b -= Math.floor(b);
    0 > b && (b += 1);
    return 29.530588853 * b;
  };
  var woy = function(yy,mm,dd) {
    var date = new Date(yy,mm-1,dd);
    date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
    var week1 = new Date(date.getFullYear(), 0, 4);
    return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
  };

  a || m || j || h || min ? (!m && (m = 1), !j && (j = 1), !h && (h = 0), !min && (min = 0), this.Now = new Date(a, m - 1, j, h, min)) : this.Now = new Date()
  this.Day = this.Now.getDate();
  this.DayInWeek = 0 == this.Now.getDay() ? 7 : this.Now.getDay();
  this.DayInWeekName = days[this.DayInWeek];
  this.Year = this.Now.getFullYear();
  this.IsBissextile = ((this.Year % 4 === 0 && this.Year % 100 > 0) || (this.Year % 400 === 0));  
  this.Month = this.Now.getMonth() + 1;
  // (...)
  this.MoonAge = getLunarAge(this.Year, this.Month, this.Day); 
  this.NextFullMoon = this.MoonAge > 14.765294427 ? 44.29588328 - this.MoonAge : 14.765294427 - this.MoonAge;
  this.NextNewMoon = 29.530588853 - this.MoonAge;
  var mn = Math.round((this.MoonAge * 8) / 29.530588853)
 // (...)
  this.ShiftDays = function(n) {
    let d = new Date(this.Year,this.Month-1,this.Day);
    d.setDate(d.getDate() + n);
    return d
  }
}

您可能会利用 getter

例子

const RightTime = function(a,m,j,h,min) {
  
  this.Now = new Date()
  this.Year = this.Now.getFullYear();
  
  Object.assign(this, {
    get IsBissextile() {
      return (this.Year % 4 === 0 && this.Year % 100 > 0) || (this.Year % 400 === 0)
    }
  })
}

const test = new RightTime();

console.log(test.IsBissextile);

或使用现代 class 作为 Andy 推荐

例子

class RightTime {
  constructor(a,m,j,h,min) {
    this.Now = new Date()
    this.Year = this.Now.getFullYear();
    this.Month = this.Now.getMonth() + 1;
  }

  get IsBissextile() {
    return (this.Year % 4 === 0 && this.Year % 100 > 0) || (this.Year % 400 === 0)
  }
  
  get Zodiac() {
    const zodiacEmote = {
      12: "♐",
    };
    const month = this.Month;
    
    return {
      get Emote() {
        return zodiacEmote[month];
      }
    }
  }
}

const test = new RightTime();

console.log(test.IsBissextile);
console.log(test.Zodiac.Emote);

至于 saving resources,我不知道你是怎么得出结论的,但通常 运行 js profiler 会更好,看看有没有潜在的罪魁祸首。