给Date的构造函数添加属性和方法

  let d = Date.prototype;
  Object.defineProperties(d, {
    'year': {
      get: function () { return this.getFullYear() },
      set: function (y) { this.setFullYear(y) }
    },
    'month': {
      get: function () { return this.getMonth() + 1 },
      set: function (m) { this.setMonth(m - 1) }
    },
    'nowTime': {
      get: function () { return `${this.getFullYear()}-${this.getMonth() + 1}-${this.getDate()} ${this.getHours()}:${this.getMinutes()}:${this.getSeconds()}` }
    }
  });
  d.asd = function asd(date) {
    return date || this.getDate();
  }
  let date = new Date();
  date.nowTime; //2019-8-18 13:45:1
  date.year; //1999
  date.month; //10
  date.year = 1999;
  date.month = 10;
  date.year; //1999
  date.month; //10
  date.nowTime; // 1999-10-18 13:45:34

 

  //各种类型的构造函数
  console.log(String.prototype);
  console.log(Number.prototype);
  console.log(Array.prototype);
  console.log(Object.prototype);
  console.log(Date.prototype);

 

posted @ 2019-08-18 13:59  _Iniesta  阅读(383)  评论(0编辑  收藏  举报